7

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.

1
  • 1
    Shame that this question doesn't pop up when people ask for CString wide to char*. The transition by CStringA is more straightforward and manageable. Commented Sep 22, 2023 at 15:04

1 Answer 1

9

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer, But It is not working I am getting Garbage Values after using statement CStringA strUtf8 = CW2A(strUtf16, CP_UTF8);
You get "garbage values" probably because you are not expecting UTF-8 bytes in the destination CStringA?
So what would be the best practice to get the desired output?
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.
Thanks It works sorry for my mistake I was using wrong Code Page

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.