考虑到所有可能的编码,是否有通用的方法将wstring转换为std::string ?

Is there any universal way to convert wstring to std::string considering all possible encoding?

本文关键字:转换 wstring std 方法 string 编码 有可能 是否 考虑到      更新时间:2023-10-16

我使用以下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转换为string ?

No。std::string的许多编码只覆盖wstring字符集的一个子集。例如,ISO-8859-1和Unicode的共同选择意味着大多数wchar_t值没有对应的char。例如,ISO-8859-1中就没有"超"字。