Code/C C++

[C++] How to: Convert Between Various String Types

Hide Code 2010. 5. 17. 14:26
'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());



1. CString -> std::string

    CString str = "hello";
    std::string stdStr = str.GetBuffer(0);

2. std::string -> CString

    std::string stdStr = "hello";
    CString str  = stdStr.c_str();



How to: Convert Between Various String Types
http://msdn.microsoft.com/library/ms235631.aspx




CString Operations Relating to C-Style Strings
http://msdn.microsoft.com/en-us/library/awkwbzyc.aspx



CString -> WCHAR*

< Method 1 >

CString str("369048");

LPTSTR pstr = str.GetBuffer(str.GetLength());
LPWSTR pwstr = new WCHAR[7];

int len = MultiByteToWideChar(CP_ACP, 0, pstr, -1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, pstr, -1, pwstr, len);

delete[] pwstr;

< Method 2 >

CString str("000888");

CHAR pstr[7];
strcpy(pstr, str.GetBuffer(str.GetLength()));

USES_CONVERSION;
WCHAR* wstr = A2W(pstr1);