Tuesday, June 24, 2008

Convert std::string to std::wstring

// std::string -> std::wstring
std::string s("string");
std::wstring ws;
ws.assign(s.begin(), s.end());

// std::wstring -> std::string
std::wstring ws(L"wstring");
std::string s;
s.assign(ws.begin(), ws.end());

13 comments:

Anonymous said...

Thanks a lot. It solves my problem.
Changsong

The Observer said...

Very neat code !! Solved my problem. Many Thanks

kizzx2 said...

This causes problems with accented characters.

For example, try converting "Música" from std::string to std::wstring

Anonymous said...

obviously that wont work. You can only go from wstring to string if the wstring only contains ASCII characters

rmacapobre said...

so how does one convert accented strings from multibyte to unicode?

Sabeesh said...

Thanks it is working. But I create a std::string like this.

std::string s("response_brücke");
and convert it like this

std::wstring ws;
ws.assign(s.begin(), s.end());

But the value of ws is not correct.
How can we convert the value of "s" into "ws".

Mijalko said...

This method is used only to convert string where characters are within ASCII character set. I don't know for method where characters like ü can be converted to something within ASCII character set. Maybe there is some third party library but I don't know.

Sabeesh said...

Thanks, I got the solution

std::wstringstream ws;
ws << s.c_str();
std::wstring sLogLevel = ws.str();

Unknown said...

Thanks a lot. Nowhere else I found such clean and properly working solution. I found it very useful.

jespa007 said...

Thanks a lot. This solved my problem too!

Unknown said...

Very good.

A little bit more compact:

// std::string -> std::wstring
std::string s("string");
std::wstring ws(s.begin(), s.end()); // uses a constructor! :-)

Maggat said...

Searched a long time for this trying to convert nordic characters Å Ä Ö from string to wstring. This solved it!

Lisa Jones said...

yes it is best command...go here