Using YAML-cpp, how to identify unknown keys?

孤人 提交于 2019-12-11 11:57:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13168043/using-yaml-cpp-how-to-identify-unknown-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!