【问题标题】:yaml-cpp : How to read this yaml file content using c++ /Linux (using yaml-cpp version = 0.6.3 )yaml-cpp :如何使用 c++ /Linux 读取此 yaml 文件内容(使用 yaml-cpp 版本 = 0.6.3 )
【发布时间】:2022-01-01 11:25:30
【问题描述】:

我正在尝试读取每个节点及其各自的内容(yaml 内容如下) 我以 belwo 错误告终。

错误: 在抛出 'YAML::TypedBadConversion

的实例后调用终止

示例代码:

#include <yaml-cpp/yaml.h>
YAML::Node config = YAML::LoadFile('yamlfile');
std::cout << config["Circles"]["x"].as<std::int64_t>();

我还尝试了其他一些方法,但也许这种 yaml 格式很复杂。我可以阅读 yaml 的示例格式,但不是我在下面提到的。

任何帮助?

sample.yaml

- Pos: sensor - pos1
  Rectangle:
    - x: -0.2
      y: -0.13
      z: 3.26
    - x: 0.005
      y: -0.13
      z: 3.2
    - x: -0.2
      y: 0.10
      z: 3.26
    - x: 0.00
      y: 0.10
      z: 3.2

【问题讨论】:

  • 'yamlfile' 应该是 "yamlfile" - 提高编译器的警告级别以捕获这样的拼写错误。 -Wall -Wextra -Werror -pedantic-errors 是一个好的开始。此外,文件名 yamlfile 不匹配 sample.yamlsample.yaml 不包含 Circles 这使得它抛出 terminate called after throwing an instance of 'YAML::TypedBadConversion&lt;long&gt;'
  • 基本上我的代码和 yaml 内容在这里不匹配。对不起,但没有添加确切的代码。购买是的,代码和 yaml 字符串匹配,包括正确的文件名。我确保这些基本内容是正确的。

标签: c++ linux yaml-cpp


【解决方案1】:

问题中的代码与您提供的sample.yaml 文件不匹配,但这里有一个示例,说明如何在sample.yaml 中提取Rectangle 中的浮点数。

#include "yaml-cpp/yaml.h"

#include <iostream>

int main() {
    try {
        YAML::Node config = YAML::LoadFile("sample.yaml");

        // The outer element is an array
        for(auto dict : config) {
            // The array element is a map containing the Pos and Rectangle keys:
            auto name = dict["Pos"];
            std::cout << "Name: " << name << '\n';

            auto rect = dict["Rectangle"];

            // loop over the positions Rectangle and print them:
            for(auto pos : rect) {
                std::cout << pos["x"].as<double>() << ",\t"
                          << pos["y"].as<double>() << ",\t"
                          << pos["z"].as<double>() << '\n';
            }
        }

    } catch(const YAML::BadFile& e) {
        std::cerr << e.msg << std::endl;
        return 1;
    } catch(const YAML::ParserException& e) {
        std::cerr << e.msg << std::endl;
        return 1;
    }
}

输出:

Name: sensor - pos1
0.2,    -0.13,  3.26
0.005,  -0.13,  3.2
-0.2,   0.1,    3.26
0,      0.1,    3.2

【讨论】:

  • 阅读成功。感谢您的努力 Ted Lyngmo
  • @Hosen 很高兴它成功了!不客气!
猜你喜欢
  • 2020-10-14
  • 1970-01-01
  • 2011-03-21
  • 2015-12-06
  • 2018-10-13
  • 2019-06-23
  • 2014-05-31
  • 2015-05-14
  • 1970-01-01
相关资源
最近更新 更多