gpt4 book ai didi

c++ - ptree get_value,名称包括 “.”

转载 作者:行者123 更新时间:2023-12-01 14:57:06 34 4
gpt4 key购买 nike

"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

}

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

最佳答案

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

您必须临时指定替代路径分隔符:

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

关于c++ - ptree get_value,名称包括 “.”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63541737/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com