gpt4 book ai didi

c++ - 使用 yaml cpp 解析 yaml

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:36 62 4
gpt4 key购买 nike

我正在尝试解析 yaml usign yaml-cpp。这是我的 yaml:

--- 
configuration:
- height: 600
- widht: 800
- velocity: 1
- scroll: 30
types:
- image: resources/images/grass.png
name: grass
- image: resources/images/water.png
name: water
version: 1.0

当我这样做

YAML::Node basenode = YAML::LoadFile("./path/to/file.yaml");
int height;
if(basenode["configuration"])
if(basenode["configuration"]["height"]
height = basenode["configuration"]["height"].as<int>();
else
cout << "The node height doesn't exist" << endl;
else
cout << "The node configuration doesn't exist" << endl;

我收到消息:“节点高度不存在”。我如何访问该字段(以及其他字段?)

非常感谢!

最佳答案

您在 - 中使用的语法创建数组元素。这意味着您正在创建(以 JSON 表示法):

{configuration: [{height: 600}, {width: 800}, {velocity: 1}, {scroll: 30}]}

但是你想要的是:

{configuration: {height: 600, width: 800, velocity: 1, scroll: 30}}

幸运的是,解决方案很简单。只需删除错误的 - 字符:

---
configuration:
height: 600
width: 800
velocity: 1
scroll: 30
types:
- image: resources/images/grass.png
name: grass
- image: resources/images/water.png
name: water
version: 1.0

请注意,我还修复了 widht 到 width 的拼写错误,并删除了 version: 1.0

之前的多余空格

如果您想知道如何实际访问您现在的配置,您必须进行数组访问:

int height = basenode["configuration"][0]["height"].as<int>();
int height = basenode["configuration"][1]["width"].as<int>();

显然,如果您真的想要这样,这将是相当令人讨厌的,因为这意味着您不再可以使用键,而是必须处理顺序问题或重新处理配置以摆脱数组级别。

关于c++ - 使用 yaml cpp 解析 yaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32492397/

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