如何转换CString和:: std :: string :: std :: wstring彼此? [英] How to convert CString and ::std::string ::std::wstring to each other?
问题描述
CString
非常方便,而 std :: string
与STL容器更兼容。
我使用 hash_map
。但是, hash_map
不支持 CString
作为键,所以我想转换 CString
到
std :: string
。
CString
is quite handy, while std::string
is more compatible with STL container.
I am using hash_map
. However, hash_map
does not support CString
as key, so I want to convert CString
into std::string
.
编写 CString
散列函数似乎需要很多时间。
Writing a CString
hash function seems to take a lot of time.
CString -----> std::string
我该如何做?
std::string -----> CString:
inline CString toCString(std::string const& str)
{
return CString(str.c_str());
}
我是对吗?
编辑:
以下是更多问题:
如何将 wstring
, CString
彼此转换?
//wstring -> CString,
std::wstring src;
CString result(src.c_str());
//CString->wstring.
CString src;
::std::wstring des(src.GetString());
是否有任何问题?
如何转换 std :: wstring
, std :: string
/ p>
How can I convert std::wstring
, std::string
to each other?
推荐答案
根据 CodeGuru :
CString
到 std: :string
:
CString cs("Hello");
std::string s((LPCTSTR)cs);
但是 std :: string
不能总是从
LPCTSTR
构造。
由于 std :: string
只能构造 LPSTR
/ LPCSTR
,使用VC ++ 7.x或更高版本的程序员可以使用转换类,例如 CT2CA
作为中介。
As std::string
can construct only from LPSTR
/ LPCSTR
, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA
as an intermediary.
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
std :: string
至 CString
: (摘自 Visual Studio的CString常见问题... )
std::string s("Hello");
CString cs(s.c_str());
CStringT
字符串。即它可以从 char *
(即 LPSTR
)或从 wchar_t *
( LPWSTR
)。
CStringT
can construct from both character or wide-character strings. i.e. It can convert from char*
(i.e. LPSTR
) or from wchar_t*
(LPWSTR
).
换句话说,char- > CStringT )ie CStringA
, wchar_t
/ code>和 TCHAR
-specialization CString
可以从 char
或宽字符,空终止(null终止在这里非常重要)字符串源。
Althoug 不可见修改null终止部分 :
In other words, char-specialization (of CStringT
) i.e. CStringA
, wchar_t
-specilization CStringW
, and TCHAR
-specialization CString
can be constructed from either char
or wide-character, null terminated (null-termination is very important here) string sources.
Althoug IInspectable amends the "null-termination" part in the comments:
不需要NUL终止。
CStringT
具有包含显式长度参数的转换构造函数。这也意味着您可以从std :: string
构造具有嵌入式NUL的对象的
字符。CStringT
NUL-termination is not required.
CStringT
has conversion constructors that take an explicit length argument. This also means that you can constructCStringT
objects fromstd::string
objects with embeddedNUL
characters.
这篇关于如何转换CString和:: std :: string :: std :: wstring彼此?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!