gpt4 book ai didi

c++ - 使用yaml-cpp解析YAML文件

转载 作者:行者123 更新时间:2023-12-02 10:30:11 29 4
gpt4 key购买 nike

我正在使用yaml-cpp 0.3.0(旧的API版本)来解析yaml文件(这是我从here获得的)。
这是yaml文件:

- name: Ogre
position: [0, 5, 0]
powers:
- name: Club
damage: 10
- name: Fist
damage: 8
- name: Dragon
position: [1, 0, 10]
powers:
- name: Fire Breath
damage: 25
- name: Claws
damage: 15
- name: Wizard
position: [5, -3, 0]
powers:
- name: Acid Rain
damage: 50
- name: Staff
damage: 3
现在,我尝试使用以下代码解析权力名称和损失:
#include "yaml-cpp/yaml.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

// our data types
struct Vec3 {
float x, y, z;
};

struct Power {
std::string name;
int damage;
};

struct Monster {
std::string name;
Vec3 position;
std::vector <Power> powers;
};

// now the extraction operators for these types
void operator >> (const YAML::Node& node, Vec3& v) {
node[0] >> v.x;
node[1] >> v.y;
node[2] >> v.z;
}

void operator >> (const YAML::Node& node, Power& power) {
node["name"] >> power.name;
node["damage"] >> power.damage;
}

void operator >> (const YAML::Node& node, Monster& monster) {
node["name"] >> monster.name;
node["position"] >> monster.position;
const YAML::Node& powers = node["powers"];
for(unsigned i=0;i<powers.size();i++) {
Power power;
powers[i] >> power;
monster.powers.push_back(power);
}
}

int main()
{
std::ifstream fin("robot.yaml");
YAML::Parser parser(fin);
YAML::Node doc;
parser.GetNextDocument(doc);
for(unsigned i=0;i<doc.size();i++) {
Power power;
doc[i] ["powers"] >> power;
std::cout << power.name << "\n";
std::cout << power.damage << "\n";
}

return 0;
}
看来我的代码显示这样的错误:
terminate called after throwing an instance of 'YAML::TypedKeyNotFound<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >'
what(): yaml-cpp: error at line 4, column 5: key not found: name
Aborted (core dumped)
请帮助我理解为什么我不能解析powers元素。
并请向我解释,因为我是编码新手,所以如何解析一个代码中的所有键和值。

最佳答案

所以问题在这里:

  doc[i] ["powers"] >> power;
doc[i]["powers"]没有索引“名称”:
  • name: Ogre
    position: [0, 5, 0]
    powers:
    • name: Club
      damage: 10
    • name: Fist
      damage: 8

“-”表示项目。因此,类似于 doc[i],您首先需要索引:
Power power;
doc[i]["powers"][0] >> power;
std::cout << power.name //outputs "Club"
但是我假设您希望每个项目都具有所有功能,因此您需要另一个显式的for循环:
for (unsigned i = 0; i < doc.size(); i++)
{
for (unsigned j = 0; j < doc[i]["powers"].size(); ++j)
{
Power power;
doc[i]["powers"][j] >> power;
std::cout << power.name << "\n";
std::cout << power.damage << "\n";
}
}
但这有点矫kill过正。最好直接使用 Monster -class,因为功效值已存储在此处:
for(unsigned i=0;i<doc.size();i++) {
Monster monster;
doc[i] >> monster;

for (auto& power : monster.powers) // range-for loop
{
std::cout << power.name << "\n";
std::cout << power.damage << "\n";
}
std::cout << monster.name << "\n";
}
也许这是一个好的开始。答案的继续取决于您要实现的目标。

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

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