【问题标题】:Why cannot I convert a string with an en dash into a wstring?为什么我不能将带有破折号的字符串转换为 wstring?
【发布时间】:2021-07-27 03:56:37
【问题描述】:

以下代码失败,我似乎无法弄清楚原因。

std::string s = "–";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(s);

我尝试阅读 UTF-8,但无法弄清楚。将初始字符串存储为 wstring,将其转换为字符串,然后将其转换回正确的结果。

std::wstring ws = L"–";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string narrow = converter.to_bytes(ws);
std::wstring wide = converter.from_bytes(narrow);

【问题讨论】:

标签: c++ string unicode utf-8


【解决方案1】:

很可能,您的 C++ 源文件未保存为 UTF-8,或者编译器未将其解释为 UTF-8,无论哪种方式都会导致 "–" 在运行时实际上不代表 U+2013 EN DASH。您可以在运行时轻松验证这一点,例如使用调试器,或者仅打印出 string 的原始字节。

确保您的 C++ 文件以 UTF-8 保存,并编译为 UTF-8。或者尝试使用此代码:

std::string s = u8"–";

或者:

std::string s = "\xE2\x80\x93";

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 2010-09-16
    • 2021-03-28
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多