Search code examples
c++linuxspecial-characterssubstrwstring

c++ can't convert string to wstring


I would like to convert a string variable to wstring due to some german characters that cause problem when doing a substr over the variable. The start position is falsified when any these special characters is present before it. (For instance: for "ä" size() returns 2 instead of 1)

I know that the following conversion works:

wstring ws = L"ä";

Since, I am trying to convert a variable, I would like to know if there is an alternative way for it such as

wstring wstr = L"%s"+str //this is syntaxically wrong, but wanted sth alike

Beside that, I have already tried the following example to convert string to wstring:

string foo("ä"); 
wstring_convert<codecvt_utf8<wchar_t>> converter;
wstring wfoo = converter.from_bytes(foo.data());
cout << foo.size() << endl;
cout << wfoo.size() << endl;

, but I get errors like

‘wstring_convert’ was not declared in this scope

I am using ubuntu 14.04 and my main.cpp is compiled with cmake. Thanks for your help!


Solution

  • The solution from "hahakubile" worked for me:

    std::wstring s2ws(const std::string& s) {
        std::string curLocale = setlocale(LC_ALL, ""); 
        const char* _Source = s.c_str();
        size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
        wchar_t *_Dest = new wchar_t[_Dsize];
        wmemset(_Dest, 0, _Dsize);
        mbstowcs(_Dest,_Source,_Dsize);
        std::wstring result = _Dest;
        delete []_Dest;
        setlocale(LC_ALL, curLocale.c_str());
        return result;
    }
    

    But the return value is not 100% correct:

    string s = "101446012MaßnStörfall   PAt  #Maßnahme Störfall                      00810000100121000102000020100000000000000";
    wstring ws2 = s2ws(s);
    cout << ws2.size() << endl; // returns 110 which is correct
    wcout << ws2.substr(29,40) << endl; // returns #Ma�nahme St�rfall with symbols
    

    I am wondering why it replaced german characters with symbols.

    Thanks again!