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

YAML file found, but unable to parse content

我正在尝试使用 yaml-cpp (https://github.com/jbeder/yaml-cpp) 解析 YAML 配置文件,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
...

但结果总是:

Window not found

加载成功,但是“config”节点对象的内容似乎是空的。我做错了什么?

你有variable shadowing:

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