如何检测Boost.PropertyTree的解析/读取失败?

Fre*_*red 6 c++ boost

文档并没有真正说明.

我知道我可以把它交给ifstream,所以我可以检查以确保它是开放的,所以这种情况主要是处理的.

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

如何检测文件格式是否错误?有什么办法,我得到的诊断信息,如其中的解析失败了吗?

Evg*_*yuk 10

抓住例外.Base 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

<unspecified file>(2): '=' character not found in line
Run Code Online (Sandbox Code Playgroud)