ptree get_value,其名称包括“.". [英] ptree get_value with name including "."

查看:62
本文介绍了ptree get_value,其名称包括“.".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"A": "1"
"A.B": "2"
"A.C": "3"

如果我通过ptree进行迭代,如何获取 A.B 的值.如果我尝试以获得 pt.get_child("A \ .B").get_value< std :: string>()的值.我收到以下异常

How to get the value of A.B if i iterate through the ptree it works. if i try to get value of pt.get_child("A\.B").get_value<std::string>(). i get the following exception

terminate called after throwing an instance of boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::ptree_bad_path> >'
      what():  No such node

请在下面找到完整的代码

please find the complete code below

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
#include <string>
#include <iterator>

using boost::property_tree::ptree;

/* Indent Json Output */
std::string indent(int level) {
    std::string s;
    for (int i = 0; i < level; i++) s += "  ";
    return s;
}

/* Print tree in json format */
void printTree(ptree & pt, int level) {
    if (pt.empty()) {
        std::cerr << "\"" << pt.data() << "\"";
    } else {
        if (level) std::cerr << std::endl;
        std::cerr << indent(level) << "{" << std::endl;
        for (ptree::iterator pos = pt.begin(); pos != pt.end();) {
            std::cerr << indent(level + 1) << "\"" << pos-> first << "\": ";

            printTree(pos->second, level + 1);
            ++pos;
            if (pos != pt.end()) {
                std::cerr << ",";
            }
            std::cerr << std::endl;
        }
        std::cerr << indent(level) << " }";
    }
    return;
}

int main()
{
ptree pt;
read_ini("sample.ini", pt);
printTree(pt, 0);
std::cout << pt.get_child("A.B").get_value<std::string>() << std::endl; //tries to resolve A.B to two nodes    
std::cout << pt.get_child("A\\.B").get_value<std::string>() << std::endl; //error

}

sample.ini

sample.ini

A=1
A.B=2
A.C=3

推荐答案

可以使用替代路径定界符,但这有点棘手,而且没有很好的记录.

You can use alternative path delimiters, but it's a bit tricky and not very well documented.

您必须临时指定备用路径分隔符:

You have to temporarily specify an alternative path separator:

在Coliru上直播

#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
using boost::property_tree::ptree;

int main() {
    ptree pt;

    pt.put("a.b", "first");
    pt.put(ptree::path_type("a|complicated.name", '|'), "second");

    write_ini(std::cout, pt);
}

打印

[a]
b=first
complicated.name=second

这篇关于ptree get_value,其名称包括“.".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆