2009. 1. 9. 18:37

[C/C++] CString을 std::string으로 바꾸는 법 (CString to std::string)

VC++ 6을 사용하던 시절에는 CString에서 std::string으로 바꾸는 것을 다음과 같이 사용하였다.

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

하지만 Visual Studio 2005로 넘어오면서 UNICODE가 기본이다 보니 위와 같은 코드가 동작하지 않을 수 있다. 원문에는 다음과 같이 적혀있다.

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 str("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString(str);
// Construct a std::string using the LPCSTR input
std::string
s(pszConvertedAnsiString);

출처 : http://www.codeguru.com