How to convert CString and ::std::string ::std::wstring to each other?


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.

Writing a CString hash function seems to take a lot of time.

CString -----> std::string

How can I do this?

std::string -----> CString:

inline CString toCString(std::string const& str)
    return CString(str.c_str()); 

Am I right?


Here are more questions:

How can I convert wstring, CString to each other?

//wstring -> CString,
std::wstring src;
CString result(src.c_str());
CString src;
::std::wstring des(src.GetString());

Is there any problem?

How can I convert std::wstring, std::string to each other?

5/20/2011 3:28:33 PM

Accepted Answer

According to CodeGuru:

CString to std::string:

CString cs("Hello");
std::string s((LPCTSTR)cs);

BUT: 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.

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 to CString: (From Visual Studio's CString FAQs...)

std::string s("Hello");
CString cs(s.c_str());

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).

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-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.

5/23/2017 12:18:25 PM

Solve that by using std::basic_string<TCHAR> instead of std::string and it should work fine regardless of your character setting.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow