ptree get_value с именем, включающим "." - PullRequest
0 голосов
/ 11 мая 2018
"A": "1"
"A.B": "2"
"A.C": "3"

Как получить значение 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

}

sample.ini

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

1 Ответ

0 голосов
/ 11 мая 2018

Вы можете использовать альтернативные разделители пути, но это немного сложно и не очень хорошо документировано.

Вам необходимо временно указать альтернативный разделитель пути:

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
...