【发布时间】:2016-12-27 19:49:24
【问题描述】:
我想将utf8 字符存储在我的std::strings 中。为此,我使用了boost::locale 转换例程。
在我的第一次测试中,一切都按预期工作:
#include <boost/locale.hpp>
std::string utf8_string = boost::locale::conv::to_utf<char>("Grüssen", "ISO-8859-15");
std::string normal_string = boost::locale::conv::from_utf(utf8_string, "ISO-8859-15");
预期的结果是:
utf8_string = "Grüssen"
normal_string = "Grüssen"
为了摆脱将“ISO-8859-15”作为字符串传递,我尝试改用std::locale。
// Create system default locale
boost::locale::generator gen;
std::locale loc=gen("ISO8859-15");
std::locale::global(loc);
// This is needed to prevent C library to
// convert strings to narrow
// instead of C++ on some platforms
std::ios_base::sync_with_stdio(false);
std::string utf8_string = boost::locale::conv::to_utf<char>("Grüssen", std::locale());
std::string normal_string = boost::locale::conv::from_utf(utf8_string, std::locale());
但结果并不如预期:
utf8_string = "Gr|ssen"
normal_string = "Gr|ssen"
我使用 std::locale 和生成器有什么问题?
(编译器VC2015,字符集多字节)
【问题讨论】:
-
如何检查结果? “期望”
utf8_string = "Grüssen"很奇怪,因为本质上你“期望”在那里解码错误。另外,源文件编码是什么?如果不是 latin1,那就错了。 -
我使用 VC2015 调试器对其进行了检查,并使用 win32 TextOutA 打印了从 utf8 转换回来的 normal_string。 Notepad++ 告诉我文件编码是 ANSI。好吧,看到 utf_8 字符串 Grüssen" 并不奇怪,因为 "Grüsse" 是 utf8 编码的 Grüsse 的外观,当您使用期望 iso8859-1 的东西渲染它时。所以这里使用 std::locale 有什么问题和为什么第二个版本有效?