5

I am working on one project where I have stucked on one problem of converting CStringW to CStringA for multibyte string like Japanese Language.

I am loading the string from string resources using LoadString() Method. I have tried following code but it does not seem to work.

CStringW csTest;
csTest.LoadString(JAPANESE_STRING);
CStringA Msg = CStringA(csTest); // Msg has been returned blank string

And

std::string Msg = CW2A(csTest);// Msg has been returned blank string

I have also tried wcstombs() too.

Can anyone tell me how I can convert CStringW to CString? Thanks in advance.

A B
  • 1,461
  • 2
  • 19
  • 54

1 Answers1

7

CStringW stores Unicode UTF-16 strings.

What encoding do you expect for your CStringA?

Do you want UTF-8?
In this case, you can do:

// strUtf16 is a CStringW.
// Convert from UTF-16 to UTF-8
CStringA strUtf8 = CW2A(strUtf16, CP_UTF8);

Talking about CStringA without specifying an encoding doesn't make sense.

The second parameter of CW2A is a what is passed to WideCharToMultiByte() Win32 API as CodePage (note that CW2A is essentially a convenient safe C++ RAII wrapper around this API). If you follow this API documentation, you can find several "code page" values (i.e. encodings).

stenliis
  • 337
  • 8
  • 22
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • Thanks for the answer, But It is not working I am getting Garbage Values after using statement `CStringA strUtf8 = CW2A(strUtf16, CP_UTF8);` – A B Feb 26 '14 at 09:47
  • You get "garbage values" probably because you are not expecting UTF-8 bytes in the destination `CStringA`? – Mr.C64 Feb 26 '14 at 10:35
  • So what would be the best practice to get the desired output? – A B Feb 26 '14 at 10:43
  • 2
    The "best practice" would be that you clarify to yourself and in your question _what encoding_ you expect as _"the desidered output"_, and specify the proper "code page" value accordingly. – Mr.C64 Feb 26 '14 at 10:49
  • Thanks It works sorry for my mistake I was using wrong Code Page – A B Feb 26 '14 at 10:58