【问题标题】:How to detect parse/read failure of Boost.PropertyTree?如何检测 Boost.PropertyTree 的解析/读取失败?
【发布时间】:2012-11-20 17:11:30
【问题描述】:

文档并没有真正说明。

我知道我可以给它一个 ifstream,所以我可以检查它以确保它是打开的,这样大部分情况都会得到处理。

但是当做 boost::property_tree::ini_parser::read_ini(ifstream_object,property_tree_object);

如何检测文件格式是否错误?有什么方法可以让我获取诊断信息,例如哪里解析失败?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    只捕获异常。基础 PropertyTree 异常类是 boost::property_tree::ptree_error,它派生自 std::runtime_error,它有两个后代:ptree_bad_dataptree_bad_path

    示例:

    #include <boost/property_tree/ini_parser.hpp>
    #include <boost/property_tree/ptree.hpp>
    #include <iostream>
    #include <sstream>
    
    int main()
    {
        using namespace std;
        using namespace boost;
        using namespace property_tree;
    
        stringstream ss;
        ss << "good = value" << endl;
        ss << "bad something" << endl;
        try
        {
            ptree root;
            read_ini(ss, root);
        }
        catch(const ptree_error &e)
        {
            cout << e.what() << endl;
        }
    }
    

    输出是:

    <unspecified file>(2): '=' character not found in line
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 2011-09-13
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多