且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转换CString和:: std :: string :: std :: wstring彼此?

更新时间:2022-03-10 18:23:03

根据 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 construct CStringT objects from std::string objects with embedded NUL characters.