考虑到所有可能的编码,是否有通用的方法将wstring转换为std::string ?
Is there any universal way to convert wstring to std::string considering all possible encoding?
我使用以下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中就没有"超"字。
相关文章:
- 将日语 wstring 转换为 std::string
- 从 uint32_t 转换为 wchar_t 并存储在 wstring 中时出现访问冲突
- 如何将std::wstring转换为char const[]
- 将utf16宽std::wstring转换为utf8窄std::string以获得罕见字符时出现问题
- 将 char* argv[] 转换为 wstring
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 在 C++ 中将 utf8 wstring 转换为窗口中的字符串
- 如何将 wstring 转换为 wchar_t*?C++
- 如何从 LPWSTR** 转换为 std::vector<std::wstring>
- 从 std::wstring 转换为 jstring
- 将 std::u16string 转换为 std::wstring,无需复制
- 如何将WSTRING中的Unix时间戳转换为char数组中格式的日期
- 转换一个带有UTF8 WSTRING控制台的装饰的字符串
- 如何将平台^字符串转换为wstring,然后与L字符串连接
- 在窗口上将格式化的 C 字符串和参数转换为 wstring
- 为什么我的 BSTR 到 std::wstring 的转换这么慢?我的测试仪不好吗?
- 在std::string和std::wstring之间转换的多平台方式
- 正在将std::wstring转换为const wchar_t x[]
- 使用字符串构造函数从wstring转换为字符串时,是否没有可能的数据丢失
- 将 std::wstring 转换为 SQLWCHAR *