我需要将某个 std::string 转换为 WCHAR,请问有人知道怎么做吗?感谢任何帮助。
string narrow_string("A string");
wstring wide_string = wstring(narrow_string.begin(), narrow_string.end());
const wchar_t* result = wide_string.c_str();
// See https://dev59.com/Q1gR5IYBdhLWcg3wGaEK
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);
}
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;
}
wchar_t
用于存储宽字符,而wstring
用于存储宽字符串。您不能将string
转换为wchar_t
,您是想将string
转换为wstring
还是wchar_t*
? - Mo Abdul-Hameed