amiltonjr
amiltonjr

Reputation: 323

MFC - How to convert WCHAR to CString?

Is it possible to convert WCHAR to CString? I need to do that, or even convert it to char or char*.

Thanks!

Upvotes: 2

Views: 12944

Answers (3)

Amit G.
Amit G.

Reputation: 2674

CString is OK with both CHAR & WCHAR. In other places, for example std::string & std::wstring, use the MFC String Conversion Macro: CW2A(pszW)

CHAR B[32]{ "The Matrix Has You" };
WCHAR WB[32]{ L"Wake up, Neo." };
std::string str;
std::wstring wstr{ L"Follow the White Rabbit" };

// std::string from std::wstring:
str = CW2A(wstr.c_str());

// CString (OK with both CHAR & WCHAR):
CString str1{ B };
CString str2{ WB };
CString str3{ str.c_str() };
CString str4{ wstr.c_str() };

// std::string from CString:
str = CW2A(str1);

-

The set of MFC generic macros is listed below:

A2CW   (LPCSTR)  -> (LPCWSTR)  
A2W    (LPCSTR)  -> (LPWSTR)  
W2CA   (LPCWSTR) -> (LPCSTR)  
W2A    (LPCWSTR) -> (LPSTR)  

-

ATL and MFC String Conversion Macros

Upvotes: 2

Pradeep Raja
Pradeep Raja

Reputation: 49

CString has constructors which accept char, char* and wchar_t. (If you do not understand the difference between 'WCHAR' and wchar_t, this will be a good reference. )

So you can do like this.

CString newCString(your_WCHAR);

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596377

CString has constructors and assignment operators that accept char* and wchar_t* data as input. So you can assign them directly to CString.

If you want to convert wchar_t* to char* look at WideCharToMultiByte()

Upvotes: 3

Related Questions