string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
如何将s的内容分配给ws?
搜索谷歌并使用了一些技术,但他们不能分配确切的内容。内容被扭曲了。
当前回答
你的问题不明确。严格来说,这个例子是一个语法错误。然而,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.
其他回答
根据我自己的测试(在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宏后-最好尽快返回,因此堆栈将从临时转换中释放出来。
int StringToWString(std::wstring &ws, const std::string &s)
{
std::wstring wsTmp(s.begin(), s.end());
ws = wsTmp;
return 0;
}
您可以使用boost路径或std路径;这样就简单多了。 Boost路径更容易用于跨平台应用程序
#include <boost/filesystem/path.hpp>
namespace fs = boost::filesystem;
//s to w
std::string s = "xxx";
auto w = fs::path(s).wstring();
//w to s
std::wstring w = L"xxx";
auto s = fs::path(w).string();
如果你喜欢使用std:
#include <filesystem>
namespace fs = std::filesystem;
//The same
c++旧版本
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
//The same
代码内仍然实现了一个转换器,你不必解开细节。
这是我的超级基本解决方案,可能并不适用于所有人。但对很多人都适用。
它需要使用指南支持库。 这是一个非常官方的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)
使用Boost。地区:
ws = boost::locale::conv::utf_to_utf<wchar_t>(s);