How to convert std::string to WCHAR

23,905

Solution 1

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();

Solution 2

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;
}
Share:
23,905

Related videos on Youtube

sharpchain
Author by

sharpchain

Updated on October 22, 2020

Comments

  • sharpchain
    sharpchain over 3 years

    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

    • Mo Abdul-Hameed
      Mo Abdul-Hameed over 7 years
      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, do you mean that you want to convert string to wstring or to wchar_t*?
    • Malcolm McLean
      Malcolm McLean over 7 years
      Just access the characters with the [] operator and cast.
  • Přemysl J.
    Přemysl J. over 3 years
    This only works correctly with ASCII characters. In practice.
  • Přemysl J.
    Přemysl J. over 3 years
    Thinking of it, it's incorrect even for ASCII, e.g. Big-5 happily overlaps.