Unable to convert the CStringW to CStringA
Asked Answered
G

1

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.

Goldie answered 26/2, 2014 at 9:31 Comment(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.Lanford
H
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).

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

© 2022 - 2024 — McMap. All rights reserved.