【问题标题】:Iterate in YAML在 YAML 中迭代
【发布时间】:2015-09-09 22:55:15
【问题描述】:

我有以下 YAML:

Configuracion:
  vel_personaje: 3
  merge_scroll: 30


Tipos:
    nombre: arbol
    imagen: img/tree
    ancho_base: 2
    alto_base: 2
    pixel_ref_x: 30
    pixel_ref_y: 40
    fps: 10
    delay: 5

    nombre: casa
    imagen: img/house

    nombre: auto
    imagen: img/tree
    ancho_base: 2
    alto_base: 2

问题是我可以拥有任意数量的“Tipos”,但有时它们有 8 个参数,有时只有 2 个,或者这两个参数之间的任何数字。我试图弄清楚如何使用 yaml-cpp 读取这些值,但我无法做到。我尝试了以下方法,但没有运气。

while (contador < tipos_size){

    try {
        name = tipos["nombre"].as<string>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        name = "pepe";
    }

    try {
        imagen = tipos["imagen"].as<string>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        imagen = "img/def";
    }

    try {
        ancho_base = tipos["ancho_base"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        ancho_base = 1;
    }

    try {
        alto_base = tipos["alto_base"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        alto_base = 1;
    }

    try {
        pixel_ref_x = tipos["pixel_ref_x"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        pixel_ref_x = 10;
    }

    try {
        pixel_ref_y = tipos["pixel_ref_y"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        pixel_ref_y = 10;
    }

    try {
        fps = tipos["fps"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        fps = 24;
    }

    try {
        delay = tipos["delay"].as<int>();
        contador++;
    } catch (YAML::Exception& yamlException) {
        delay = 100;
    }

我将不胜感激。谢谢!

编辑代码:

    for (YAML::Node tipo : tipos) {

    try {
        name = tipo["nombre"].as<string>();
    } catch (YAML::Exception& yamlException) {
        name = "pepe";
    }

【问题讨论】:

    标签: c++ yaml yaml-cpp


    【解决方案1】:

    看起来您希望Tipos 是一系列地图,而不是地图:

    Configuracion:
      vel_personaje: 3
      merge_scroll: 30
    
    
    Tipos:
    
      - nombre: arbol
        imagen: img/tree
        ancho_base: 2
        alto_base: 2
        pixel_ref_x: 30
        pixel_ref_y: 40
        fps: 10
        delay: 5
    
      - nombre: casa
        imagen: img/house
    
      - nombre: auto
        imagen: img/tree
        ancho_base: 2
        alto_base: 2
    

    你可以像这样迭代:

    for (YAML::Node tipo : tipos) {
      // handle tipo
    }
    

    【讨论】:

    • 感谢您的回答!那就是我正在寻找的东西。但是知道我有一个不同的问题,我相信你可以帮助我。这样做: for (YAML::Node tipo : tipos) { try { name = tipo["nombre"].as( ); } catch (YAML::Exception& yamlException) { name = "pepe";它总是通过“catch”部分进入..并且不从文件中读取值。你知道可以是什么吗?我给你留下了在主要问题上缩进编辑好的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2023-02-01
    • 2019-08-05
    相关资源
    最近更新 更多