【问题标题】:Can't read nested maps (raises YAML::InvalidScalar)无法读取嵌套映射(引发 YAML::InvalidScalar)
【发布时间】:2010-06-28 18:59:18
【问题描述】:

我有一个类(包含一些标量值和一个浮点向量),我想读取和写入一个实例作为另一个映射的值。

// 写 out > 键; it.second() >> 值; if (key.compare("my_queue") == 0) { *它>>我的队列; } }

编写这门课效果很好,但无论我做什么,我似乎都无法阅读它。它不断抛出 InvalidScalar。

捕获 YAML::InvalidScalar yaml-cpp:第 20 行第 13 列错误:无效标量

这是输出(用 yaml-cpp 编写而没有报告任何错误)看起来像:

其他号码:80 我的队列: 尺寸:20 数据: - 3.5 - -1 - -1.5 - 0.25 - -24.75 - -5.75 - 2.75 - -33.55 - 7.25 - -11 - 15 - 37.5 - -3.75 - -28.25 - 18.5 - 14.25 - -36.5 - 6.75 - -0.75 - 14 最大尺寸:20 平均值:-0.0355586 标准开发:34.8981 even_more_data:1277150400

文档似乎说这是受支持的用法,嵌套映射,在这种情况下,将序列作为值之一。它抱怨它是一个 InvalidScalar,尽管我做的第一件事告诉它这是一张地图:

YAML::Emitter& 运算符

有人发现这有问题吗?

【问题讨论】:

  • 附注key.compare("my_queue") == 0可以写成key == "my_queue"

标签: yaml-cpp


【解决方案1】:

当您阅读 YAML 时:

std::string key, value;
it.first() >> key;
it.second() >> value; // ***
if (key.compare("my_queue") == 0) {
  *it >> my_queue;
}

标记的行尝试将键/值对的读取为标量(std::string);这就是为什么它告诉你它是一个无效的标量。相反,你想要:

std::string key, value;
it.first() >> key;
if (key.compare("my_queue") == 0) {
  it.second() >> my_queue;
} else {
  // ...
  // for example: it.second() >> value;
}

【讨论】:

  • 我以为我很密集!当然,在我尝试打电话给我的接线员之前,我会将它发送到字符串。 脸红 谢谢杰西!
【解决方案2】:
YAML::Node internalconfig_yaml = YAML::LoadFile(configFileName);
const YAML::Node &node = internalconfig_yaml["config"];
for(const auto& it : node )
{
    std::cout << "\nnested Key: " << it.first.as<std::string>() << "\n";
    if (it.second.Type() == YAML::NodeType::Scalar)
    {
        std::cout << "\nnested value: " << std::to_string(it.second.as<int>()) << "\n";
    }
    if (it.second.Type() == YAML::NodeType::Sequence)
    {
        std::vector<std::string> temp_vect;
        const YAML::Node &nestd_node2 = it.second;
        for(const auto& it2 : nestd_node2)
        {
            if (*it2)
            {
                std::cout << "\nnested sequence value: " << it2.as<std::string>() << "\n";
                temp_vect.push_back(it2.as<std::string>());
             }
        }
        std::ostringstream oss;
        std::copy(temp_vect.begin(), temp_vect.end(),                 
                  std::ostream_iterator<std::string>(oss, ","));
        std::cout << "\nnested sequence as string: " <<oss.str() << "\n";
    }
}
if (it2.second.Type() == YAML::NodeType::Map)
{
 // Iterate Recursively again !!
 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多