【问题标题】:Using boost locale generator correctly正确使用 boost 语言环境生成器
【发布时间】: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 有什么问题和为什么第二个版本有效?

标签: c++ boost locale utf


【解决方案1】:

boost::locale::generator 想要一个locale id,而不仅仅是一个编码(相同的编码可以被多个区域使用)。它使用的方案是language_country.encoding,所以你需要de_DE.ISO-8859-15

另外,在源代码中放入非 ASCII 字符是在玩火。小心点。

您对sync_with_stdio() 的评论也很奇怪。它只是确保缓冲区被刷新。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-02-17
  • 2012-04-23
  • 2019-01-29
  • 2022-11-13
  • 2016-07-05
  • 1970-01-01
  • 2012-12-06
  • 2019-12-07
相关资源
最近更新 更多