string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
当前回答
s2ws方法效果良好。希望有帮助。
std::wstring s2ws(const std::string& s) {
std::string curLocale = setlocale(LC_ALL, "");
const char* _Source = s.c_str();
size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete []_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
其他回答
string s =“早上好”;is an error。
你应该直接使用wstring:
wstring ws = L"おはよう";
根据我自己的测试(在windows 8上,vs2010) mbstowcs实际上可以破坏原始字符串,它只适用于ANSI代码页。If MultiByteToWideChar/WideCharToMultiByte也会导致字符串损坏-但他们倾向于用'?'问号,但mbstowcs往往会在遇到未知字符时停止,并在此时切断字符串。(我在芬兰语窗口上测试过越南字符)。
所以更喜欢Multi* windows api函数而不是模拟ansi C函数。
我还注意到,从一个代码页到另一个代码页编码字符串的最短方法不是使用MultiByteToWideChar/WideCharToMultiByte api函数调用,而是它们的模拟ATL宏:W2A / A2W。
所以如上所述的模拟函数听起来是这样的:
wstring utf8toUtf16(const string & str)
{
USES_CONVERSION;
_acp = CP_UTF8;
return A2W( str.c_str() );
}
_acp在USES_CONVERSION宏中声明。
或者在执行旧数据到新数据的转换时,我经常错过的函数:
string ansi2utf8( const string& s )
{
USES_CONVERSION;
_acp = CP_ACP;
wchar_t* pw = A2W( s.c_str() );
_acp = CP_UTF8;
return W2A( pw );
}
但请注意,这些宏使用大量的堆栈-不要为同一个函数使用for循环或递归循环-在使用W2A或A2W宏后-最好尽快返回,因此堆栈将从临时转换中释放出来。
你的问题不明确。严格来说,这个例子是一个语法错误。然而,std::mbstowcs可能是您正在寻找的。
它是一个c库函数,操作缓冲区,但这里有一个易于使用的习语,由Mooing Duck提供:
std::wstring ws(s.size(), L' '); // Overestimate number of code points.
ws.resize(std::mbstowcs(&ws[0], s.c_str(), s.size())); // Shrink to fit.
使用Boost。地区:
ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
这是一种将字符串,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();