正确使用boost语言环境生成器

时间:2016-08-20 23:22:59

标签: c++ boost locale utf

我想在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,charset multibyte)

1 个答案:

答案 0 :(得分:1)

boost::locale::generator想要区域设置ID ,而不仅仅是编码(多个区域设置可以使用相同的编码)。它使用的方案是language_country.encoding,因此您需要de_DE.ISO-8859-15

此外,您通过在源代码中添加非ASCII字符来玩火。小心。

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

相关问题