Pages

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:

  1. Anonymous2:46 PM

    Thanks a lot. It solves my problem.
    Changsong

    ReplyDelete
  2. Very neat code !! Solved my problem. Many Thanks

    ReplyDelete
  3. This causes problems with accented characters.

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

    ReplyDelete
  4. Anonymous5:30 PM

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

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

    ReplyDelete
  6. 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".

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

    ReplyDelete
  8. Thanks, I got the solution

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

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

    ReplyDelete
  10. Thanks a lot. This solved my problem too!

    ReplyDelete
  11. 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! :-)

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

    ReplyDelete
  13. yes it is best command...go here

    ReplyDelete