string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
当前回答
使用这段代码将字符串转换为wstring
std::wstring string2wString(const std::string& s){
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
int main(){
std::wstring str="your string";
std::wstring wStr=string2wString(str);
return 0;
}
其他回答
String到wstring
std::wstring Str2Wstr(const std::string& str)
{
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
从wstring到String
std::string Wstr2Str(const std::wstring& wstr)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
从char*到wstring:
char* str = "hello worlddd";
wstring wstr (str, str+strlen(str));
从string到wstring:
string str = "hello worlddd";
wstring wstr (str.begin(), str.end());
注意,只有在被转换的字符串只包含ASCII字符时,这种方法才有效。
这是一种将字符串,wstring和混合字符串常量组合到wstring的方法。使用wstringstream类。
这并不适用于多字节字符编码。这只是一种抛弃类型安全并将std::string中的7位字符扩展到std:wstring中每个字符的下7位的愚蠢方法。只有当你有一个7位ASCII字符串并且你需要调用一个需要宽字符串的API时,这才有用。
#include <sstream>
std::string narrow = "narrow";
std::wstring wide = L"wide";
std::wstringstream cls;
cls << " abc " << narrow.c_str() << L" def " << wide.c_str();
std::wstring total= cls.str();
这是我的超级基本解决方案,可能并不适用于所有人。但对很多人都适用。
它需要使用指南支持库。 这是一个非常官方的c++库,由许多c++委员会的作者设计:
https://github.com/isocpp/CppCoreGuidelines https://github.com/Microsoft/GSL
std::string to_string(std::wstring const & wStr)
{
std::string temp = {};
for (wchar_t const & wCh : wStr)
{
// If the string can't be converted gsl::narrow will throw
temp.push_back(gsl::narrow<char>(wCh));
}
return temp;
}
我的函数所做的只是允许转换。否则抛出异常。
通过使用gsl::narrow (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es49-if-you-must-use-a-cast-use-a-named-cast)
Std::string -> wchar_t[]与安全mbstowcs_s函数:
auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());
这是我的示例代码