Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert std::string to WCHAR

I need to take an std::string that I have and convert it to a WCHAR does anyone know how to do this? Any help is appreciated

like image 879
sharpchain Avatar asked Oct 08 '16 00:10

sharpchain


Video Answer


2 Answers

Your question is vague; wchar_t is used to store a wide character, and wstring is to store a wide string. You can't convert a string to wchar_t.

But if your aim was to convert an std::string to wchar_t*, then you need to convert your std::string to an std::wstring first, then to convert your std::wstring to const wchar_t*.

string narrow_string("A string");
wstring wide_string = wstring(narrow_string.begin(), narrow_string.end());
const wchar_t* result = wide_string.c_str();
like image 92
Mo Abdul-Hameed Avatar answered Oct 16 '22 07:10

Mo Abdul-Hameed


Assuming you want to convert from the locale encoding, since you want wchar_t.

Option 1, since C++11 but deprecated in C++17:

// See https://stackoverflow.com/questions/41744559
template<class I, class E, class S>
struct codecvt_ : std::codecvt<I, E, S> { ~codecvt_ () {} };

std::wstring to_wide (const std::string &multi) {
    return std::wstring_convert<codecvt_<wchar_t, char, mbstate_t>> {}
        .from_bytes (multi);
}

Option 2, widely portable:

std::wstring to_wide (const std::string &multi) {
    std::wstring wide; wchar_t w; mbstate_t mb {};
    size_t n = 0, len = multi.length () + 1;
    while (auto res = mbrtowc (&w, multi.c_str () + n, len - n, &mb)) {
        if (res == size_t (-1) || res == size_t (-2))
            throw "invalid encoding";

        n += res;
        wide += w;
    }
    return wide;
}
like image 43
Přemysl J. Avatar answered Oct 16 '22 05:10

Přemysl J.