Konvertieren zwischen CString und std::string
Q: How to convert between 'CString' and 'std::string'?
A:
'CString' to 'std::string':
1CString cs("Hello");
2std::string s((LPCTSTR)cs);
'std::string' to 'CString':
1std::string s("Hello");
2CString cs(s.c_str());
std::string cannot always construct from a LPCTSTR i.e. the code will fail for UNICODE builds.
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.
Like this:
1CString cs ("Hello");
2
3// Convert a TCHAR string to a LPCSTR
4CT2CA pszConvertedAnsiString (cs);
5
6// construct a std::string using the LPCSTR input
7std::string strStd (pszConvertedAnsiString);