找到了YAML文件,但无法分析内容



我正在尝试使用YAML-cpp解析一个YAML配置文件(https://github.com/jbeder/yaml-cpp),Visual Studio 2019社区。

#include <iostream>
#include "yaml-cpp/yaml.h"
int main(int argc, char* argv[])
{
YAML::Node config;
try
{
YAML::Node config = YAML::LoadFile("conf.yml");
}
catch (YAML::BadFile e)
{
std::cerr << e.msg << std::endl;
return (1);
}
catch (YAML::ParserException e)
{
std::cerr << e.msg << std::endl;
return (1);
}
std::cout << config["window"] ? "Window found" : "Window not found" << std::endl;
return (0);
}

这是我的YAML文件:

---
window:
width: 1280
height: 720
...

但结果总是:

找不到窗口

加载成功,但";config";node对象似乎为空。我做错了什么?

您有变量阴影

YAML::Node config; // This is the config you print out at the end
try
{
// The below config is local to the narrow try-scope, shadowing the
// config you declared above.
YAML::Node config = YAML::LoadFile("conf.yml");
}

更正:

YAML::Node config;
try
{
config = YAML::LoadFile("conf.yml");
}

在三元运算符周围加上括号:

std::cout << (config["window"] ? "Window found" : "Window not found") << 'n';

最新更新