Question

The use case is stepping through a configuration file written in YAML. I need to check each key and parse its value accordingly. I like the idea of using random-access methods like doc["key"] >> value, but what I really need to do is warn the user of unrecognized keys in the config file, in case they, for example, misspelled a key. I don't know how to do that without iterating through the file.

I know I can do this using YAML::Iterator, like so

for (YAML::Iterator it=doc.begin(); it<doc.end(); ++it) 
{ 
   std::string key;
   it.first() >> key;
   if (key=="parameter") { /* do stuff, possibly iterating over nested keys */ }
   } else if (/* */) {
   } else {
       std::cerr << "Warning: bad parameter" << std::endl;
   }
}

but is there a simpler way to do this? My way seems to completely circumvent any error checking built into YAML-cpp, and it seems to undo all the simplicity of randomly accessing the keys.

Was it helpful?

Solution

If you're worried about a key not being there because the user misspelled it, you can just use FindValue:

if(const YAML::Node *pNode = doc.FindValue("parameter")) {
   // do something
} else {
   std::cerr << "Parameter missing\n";
}

If you genuinely want to get all keys in the map outside of your specific list, then you'll have to iterate through as you're doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top