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
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();
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With