在括号内获取内容时遇到麻烦

时间:2011-02-25 20:04:13

标签: yaml-cpp

monsters.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

的main.cpp

#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("monsters.yaml");
   YAML::Parser parser(fin);
   YAML::Node doc;
   parser.GetNextDocument(doc);
   for(unsigned i=0;i<doc.size();i++) {
      Vec3 v;
      doc[i] >> v;
      std::cout << v.x << "\n";
      std::cout << v.y << "\n";
      std::cout << v.z << "\n";
   }

   return 0;
}

我认为,如果我类似地修改代码,那么Vec3的内容将会得到满足,但事实并非如此。我做错了什么?

1 个答案:

答案 0 :(得分:0)

你的YAML文件是一系列“怪物”,而不是“矢量”。要获得“position”属性,您需要:

doc[i]["position"] >> v;

此外,您的YAML有缩进错误(顶级序列没有排列)。我假设你的文件是正确的;在这里复制时要小心。