我正在使用以下api将wstring编码为string,
string utf8_encode(const std::wstring &wstr)
{
int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, 0, 0, 0, 0);
vector<char> buf(len);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &buf[0], len, 0, 0);
return std::string(buf.begin(), buf.end());
}
只要在系统区域设置为
的Windows计算机中执行,此编码就可以正常工作英
现在,如果我尝试在日语窗口中使用它,则转换后的字符串会被破坏。我的理解是,日本窗户使用Shift-JIS编码。 如果我修改API以将代码页作为参数,那么它可以工作。
string utf8_encode(const std::wstring &wstr)
{
UINT codePage = GetACP();
int len = WideCharToMultiByte(codePage, 0, wstr.c_str(), -1, 0, 0, 0, 0);
vector<char> buf(len);
WideCharToMultiByte(codePage, 0, wstr.c_str(), -1, &buf[0], len, 0, 0);
return std::string(buf.begin(), buf.end());
}
但它再次失败如果我在Windows机器上使用日语或中文字符,默认系统区域设置为英语。基本上我必须使用CP_UTF8进行转换。如果我必须支持以下代码页怎么办?
http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
考虑到所有可能的编码,有没有通用的方法将wstring转换为字符串?
答案 0 :(得分:1)
没有。 std::string
的许多编码仅涵盖wstring
字符集的子集。例如。 ISO-8859-1
和Unicode的常见选择意味着大多数wchar_t
值没有char
等效值。例如,ISO-8859-1中没有サ。