【问题标题】:yaml-cpp read sequence in itemyaml-cpp 读取项目中的序列
【发布时间】:2015-07-12 13:12:20
【问题描述】:

如何使用 yaml-cpp 读取此 YAML 文件:

sensors:
  - id: 5
    hardwareId: 28-000005a32133
    type: 1
  - id: 6
    hardwareId: 28-000005a32132
    type: 4

我不明白我怎样才能获得sensors 项目,以使用它。

据我了解,sensorsYAML::Node。我怎样才能得到它?

更新 1:

YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& node_test1 = confg["sensors"];

for (std::size_t i = 0; i < node_test1.size(); i++) {
    const YAML::Node& node_test2 = node_test1[i];
    std::cout << "Id: " << node_test2["id"].as<std::string>() << std::endl;
    std::cout << "hardwareId: " << node_test2["hardwareId"].as<std::string>() << std::endl << std::endl;
}

此代码有效,但它是使用有关旧 api 的教程编写的。 我认为这段代码可以用迭代器重写,但我现在不知道如何。

【问题讨论】:

  • 你试过什么?阅读教程:github.com/jbeder/yaml-cpp/wiki/Tutorial 看看是否有帮助:)
  • 我已经阅读了这个教程,我找到了如何阅读序列,但是我没有找到如何阅读项目中的序列。据我了解,在我的示例中 sensors 也是节点。但是我没有找到如何使用它作为YAML::Node

标签: c++ yaml yaml-cpp


【解决方案1】:

看起来你的代码可以工作,但如果你想用迭代器重写它,你可以:

YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& sensors = config["sensors"];
for (YAML::iterator it = sensors.begin(); it != sensors.end(); ++it) {
    const YAML::Node& sensor = *it;
    std::cout << "Id: " << sensor["id"].as<std::string>() << "\n";
    std::cout << "hardwareId: " << sensor["hardwareId"].as<std::string>() << "\n\n";
}

【讨论】:

  • 我发现我需要使用YAML::const_iterator 而不是YAML::iterator
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 2016-04-01
  • 2019-09-23
相关资源
最近更新 更多