Click to See Complete Forum and Search --> : C++ String: How to convert between 'CString' and 'std::string'?


Gabriel Fleseriu
February 14th, 2003, 03:50 AM
Q: How to convert between 'CString' and 'std::string'?

A:

'CString' to 'std::string':


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


'std::string' to 'CString':


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

<br><br>

Siddhartha
May 14th, 2006, 09:20 AM
'CString' to 'std::string':


CString cs("Hello");
std::string s((LPCTSTR)cs);
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 - 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);