views:

721

answers:

3
string s = "おはよう";
wstring ws = FUNCTION(s, ws);

How would i assign the contents of s to ws?

Searched google and used some techniques but they can't assign the exact content. The content is distorted.

+3  A: 

Your question is underspecified. Strictly, that example is a syntax error. However, mbstowcs is probably what you're looking for.

It is a C function and operates on buffers, so you will need

wchar_t buf[] = new wchar_t[ s.size() ];
size_t num_chars = mbstowcs( buf, s.c_str(), s.size() );
wstring ws( buf, num_chars );
delete[] buf;
Potatoswatter
string s = "おはよう";wchar_t* buf = new wchar_t[ s.size() ];size_t num_chars = mbstowcs( buf, s.c_str(), s.size() );wstring ws( buf, num_chars );// ws = distorted
Samir
@Samir: You have to make sure the runtime encoding is the same as the compile-time encoding. You might need to `setlocale` or adjust compiler flags. I don't know because I don't use Windows, but this is why it's not a common feature. Consider the other answer if possible.
Potatoswatter
+1  A: 

string s = "おはよう"; is an error.

You should use wstring directly:

wstring ws = L"おはよう";

Mandatory unicode snowman for kicks:

Andreas Bonini
That's not going to work either. You'll have to convert those non-BMP characters to C escape sequences.
Dave Van den Eynde
@Dave: it does work if your compiler supports unicode in source files, and all the ones in the last decade do (visual studio, gcc, ...)
Andreas Bonini
Hi, regardless of the default system encoding (I may have Arabic as my default system encoding for example), what should the encoding of the source code file for L"おはよう" to work? should it be in UTF-16, or can I have UTF-8 without BOM for the .cpp file encoding?
afriza
@afriza: it doesn't really matter as long as your compile supports it
Andreas Bonini
A: 

this link

solved my problem. Hope it would help others too.

Samir
Just be aware of the "CP_ACP" parameter in that code sample. It makes the code behavior dependant on OS language settings.
Nemanja Trifunovic