【问题标题】:ptree get_value with name including "."名称包含“.”的 ptree get_value
【发布时间】:2023-03-03 04:00:01
【问题描述】:
"A": "1"
"A.B": "2"
"A.C": "3"

如果我遍历 ptree 它可以工作,如何获得 A.B 的值。如果我尝试 获得pt.get_child("A\.B").get_value<std::string>() 的值。我得到以下异常

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

请在下面找到完整的代码

#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

}

示例.ini

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

【问题讨论】:

  • 嗨,谁能告诉我为什么不赞成,需要改变什么。需要任何信息吗!?
  • 我完全同意。对于任何了解所涉及的图书馆的人来说,这是一个很好的问题。 (我不确定你的文字是否是 ini.get_child,但该示例似乎不是 INI 格式。)
  • 我添加了一个合适的例子。

标签: c++ boost ptree


【解决方案1】:

可以使用替代路径分隔符,但它有点棘手,而且没有很好的文档记录。

你必须临时指定一个替代路径分隔符:

Live On 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

【讨论】:

  • 感谢您的回复。但我正在阅读 sample.ini。很抱歉造成误解。
  • 这与答案无关。只需使用带有显式分隔符的path_type(您不使用的任何字符)。 [注意我在添加评论之前回答了。该评论只是为了回应人们对该问题的反对意见。]
  • pt.get_child(ptree::path_type("A.B", '|').get_value&lt;std::string&gt;() 谢谢这个作品
猜你喜欢
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多