【问题标题】:Boost can not find nested nodes in INI fileBoost 在 INI 文件中找不到嵌套节点
【发布时间】:2021-05-08 09:19:51
【问题描述】:

我有一个这样的ini文件;

[Sensor]
address=69
mode=1
[Sensor.Offsets]
x=65.0
y=-66.3

我正在尝试在结构中加载值:

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

void myFunc() {
    using namespace boost::property_tree;
    ptree pt;
    double x{};
    
    // Read config file
    boost::property_tree::ini_parser::read_ini("config.ini", &pt);    

    try {
        x = pt.get<double>("Sensor.Offsets.x");
    } catch (std::exception& ex) {
        spdlog::error("{}", ex.what());
        exit(-2);
    }
}

我收到错误:No such node (Sensor.Offsets.x)

知道有什么问题吗?

【问题讨论】:

    标签: c++ boost ini


    【解决方案1】:

    您需要“转义”点。点很特殊,因此您的键被解释为 [Sensor][Offsets][x],而不是 [Sensor.Offsets][x]。

    你可以强制:

    auto& so = pt.get_child({"Sensor.Offsets", '#'});
    x = so.get<double>("x");
    

    什么是简写

    auto& so = pt.get_child(
        boost::property_tree::ptree::path_type{"Sensor.Offsets", '#'});
    x = so.get<double>("x");
    

    如您所见,它使用不同的分隔符显式构造了 path_type 参数。

    现场演示

    Compiler Explorer

    #include <boost/property_tree/ini_parser.hpp>
    #include <fmt/format.h>
    
    int main()
    {
        boost::property_tree::ptree pt;
    
        std::istringstream config_ini("[Sensor]\naddress=69\nmode=1\n[Sensor.Offsets]\nx=65.0\ny=-66.3");
        read_ini(config_ini, pt);
    
        try {
            auto& so = pt.get_child({"Sensor.Offsets", '#'});
            double x = so.get<double>("x");
            double y = so.get<double>("y");
    
            fmt::print("[Sensor.Offsets].(x,y) = ({},{})\n", x, y);
        } catch (std::exception& ex) {
            fmt::print("{}\n", ex.what());
            exit(-2);
        }
    }
    

    打印

    [Sensor.Offsets].(x,y) = (65,-66.3)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2015-02-16
    相关资源
    最近更新 更多