3

I'm attempting to parse a YAML file output from Perl's YAML::Tiny using C++. As a C++ & YAML newbie, I'm using HowToParseADocument as a starting point.

The monsters.yaml file, if created by using YAML::Tiny, looks like:

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

I'm looking for help with morphing the example at HowToParseADocument to read in the modified YAML file with --- as the separator for each entry. I recopied the C++ main code below.

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++) {
      Monster monster;
      doc[i] >> monster;
      std::cout << monster.name << "\n";
   }

   return 0;
}
CanSpice
  • 34,814
  • 10
  • 72
  • 86
jim
  • 41
  • 2

1 Answers1

4

The separator --- splits the YAML file into several documents (as opposed to a single document consisting of a sequence, as in the example).

You could parse it like this:

int main()
{
   std::ifstream fin("monsters.yaml");
   YAML::Parser parser(fin);
   YAML::Node doc;
   while(parser.GetNextDocument(doc)) {
      Monster monster;
      doc >> monster;
      std::cout << monster.name << "\n";
   }

   return 0;
}
Jesse Beder
  • 33,081
  • 21
  • 109
  • 146