CString to std::string
簡單方式:
CString cs("Hello");
std::string s((LPCTSTR)cs);
但是 std::string 並非總是能用 LPCTSTR 正確的建構出來。例如, 以上的程式碼在 UNICODE 組態下 build 會失敗
由於 std::string 的標準建構元為 LPSTR / LPCSTR, 程式設計師要不就是用 VC++ 7.x 以上的版本, 或是使用轉換用的 classes 像是 CT2CA
CString cs("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA ascii(cs);
// construct a std::string using the LPCSTR input
std::string strStd(ascii);
or
CString str(_T("Hello, world!"));
CT2A ascii(str);
std::string s(ascii.m_psz);
std::string to CString
std::string s("Hello");
CString cs(s.c_str());
ps: class CStringT 能夠建構來自 character 或是 wide-character 的字串, 而且不用特別在字串的尾端特別放進 NULL, 如 std::string s(“Hello\0”);
ref: How to convert CString and ::std::string ::std::wstring to each other?
#unicode #ansi #convert #mfc