Search code examples
c++stringstdwstring

C++ issue with conversion of std::string to std::wstring - Windows vs Linux


I'm trying to convert the string "pokémon" from std::string to std::wstring using

std::wstring wsTmp(str.begin(), str.end());

This works on Windows, but on Linux it returns "pok\xffffffc3\xffffffa9mon"

How can I make it work on Linux?


Solution

  • This worked for me on POSIX.

    #include <codecvt>
    #include <string>
    #include <locale>
    
    int main() {
        
        std::string a = "pokémon";
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cv;
        std::wstring wide = cv.from_bytes(a);
        
        return 0;
    }
    

    The wstring holds the correct string at the end.

    Important note by @NathanOliver: std::codecvt_utf8_utf16 was deprecated in C++17 and may be removed from the standard in a future version.