我正在尝试解析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
Run Code Online (Sandbox Code Playgroud)
当我做
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;
Run Code Online (Sandbox Code Playgroud)
我收到消息:"节点高度不存在".我如何访问该字段(以及其他字段?)
非常感谢!
您在-创建数组元素时使用的语法.这意味着您正在创建(使用JSON表示法):
{configuration: [{height: 600}, {width: 800}, {velocity: 1}, {scroll: 30}]}
Run Code Online (Sandbox Code Playgroud)
但你想要的是:
{configuration: {height: 600, width: 800, velocity: 1, scroll: 30}}
Run Code Online (Sandbox Code Playgroud)
幸运的是,解决方案很简单.只需删除错误的-字符:
---
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
Run Code Online (Sandbox Code Playgroud)
请注意,我还修复了宽度错误并删除了一个无关的空间 version: 1.0
如果您想知道如何实际访问现在的配置,您必须进行数组访问:
int height = basenode["configuration"][0]["height"].as<int>();
int height = basenode["configuration"][1]["width"].as<int>();
Run Code Online (Sandbox Code Playgroud)
显然,如果你真的想要它,这将是相当讨厌的,因为它意味着你不再使用键,但必须要么有订单或重新处理配置以摆脱阵列级别.
| 归档时间: |
|
| 查看次数: |
3006 次 |
| 最近记录: |