zoukankan      html  css  js  c++  java
  • boost.property_tree读取中文乱码问题正确的解决方式

    开发项目的时候在使用boost,在宽字符下遇到中文乱码问题

    上网上看大家都是先转成utf8在进行解析的,例如:

    http://blog.csdn.net/hu_jiangan/article/details/49945373 中

    void Init(const wstring& fileName, wptree& ptree)
    {
      std::wifstream f(fileName);
      std::locale utf8Locale(std::locale(), new std::codecvt_utf8<wchar_t>);
      f.imbue(utf8Locale); //先转换一下
      //用wptree去解析
      property_tree::read_xml(f, ptree);
    }
    

      他的思路没有问题,并且还用了STL库,避免了boost的繁琐。

    但是在boost中对read_xml定义里包含了对xml的转换

     1 template<class Ptree>
     2     void read_xml(const std::string &filename,
     3                   Ptree &pt,
     4                   int flags = 0,
     5                   const std::locale &loc = std::locale())
     6     {
     7         BOOST_ASSERT(validate_flags(flags));
     8         std::basic_ifstream<typename Ptree::key_type::value_type>
     9             stream(filename.c_str());
    10         if (!stream)
    11             BOOST_PROPERTY_TREE_THROW(xml_parser_error(
    12                 "cannot open file", filename, 0));
    13         stream.imbue(loc);
    14         read_xml_internal(stream, pt, flags, filename);
    15     }

    所以他对xml进行了两次utf8的转换
    正确的代码其实只需要两行就可以完成

    void Init(const wstring& fileName, wptree& ptree)
    {
      std::locale utf8Locale(std::locale(), new std::codecvt_utf8<wchar_t>);
      boost::property_tree::read_xml(filename, ptree, 0, utf8Locale);
    }
    赌上我的人生为梦想,即使是臭名远扬,也要我的名字响彻天堂
  • 相关阅读:
    三、录制脚本Badboy录制脚本1
    三、录制脚本术语
    二、搭建Jmeter环境以及环境变量
    三、录制脚本Jmeter录制脚本2
    一、JMeter相关术语
    MySQL存储引擎
    创建线程CreateThread()
    关于category
    关于异常
    UIView和UIWindow
  • 原文地址:https://www.cnblogs.com/ye-ming/p/6963287.html
Copyright © 2011-2022 走看看