yaml-cpp icon indicating copy to clipboard operation
yaml-cpp copied to clipboard

Default value for optional map entries

Open tobias85 opened this issue 8 years ago • 5 comments

It seems, that the former default value mode does not work anymore: node["myParam"].as(default_value)

If the myParam key does not exist I get the error: yaml-cpp: error at line 0, column 0: invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa

Is this mode not supported anymore? I updated from 0.5.1 (Ubuntu 14.04) to 0.5.2 (Ubuntu 16.04)

tobias85 avatar May 09 '17 09:05 tobias85

Minimal example?

jbeder avatar May 09 '17 10:05 jbeder

Sorry. I was a little lazy...

This is my test.yaml:

config:
  - param: 2.0
  - param: 3.0
  - test: 4.0

The problem seems to appear when using const.

#include <yaml-cpp/yaml.h>
#include <iostream>

int main(int argc, char* argv[]) {
    YAML::Node config_yaml = YAML::LoadFile("test.yaml");

    // without const everything is fine
    // adding this code block seems to add the missing key (leaving it unset as the second loop outputs the changed default value)
/*    for (auto cameraProp : config_yaml["config"]) {
        std::cout << "param: " << std::flush;
        std::cout << cameraProp["param"].as<double>(1.0) << std::endl;
    }*/
    for (const auto cameraProp : config_yaml["config"]) {
        std::cout << "param: " << std::flush;
        std::cout << cameraProp["param"].as<double>(3.0) << std::endl;
    }
    return 0;
}

PS: It would be great if the exceptions would output the source of the error (which file could not be loaded, which key wasn't found, ...)

tobias85 avatar May 09 '17 12:05 tobias85

Or even more simple:

#include <yaml-cpp/yaml.h>
#include <iostream>

int main(int argc, char* argv[]) {
	const YAML::Node config_yaml = YAML::LoadFile("test.yaml");
    std::cout << config_yaml["param"].as<double>(1.0) << std::endl;
	return 0;
}

tobias85 avatar May 09 '17 12:05 tobias85

It seems to work.

MartinDelille avatar Aug 25 '20 18:08 MartinDelille

how to set default value?

cxwx avatar May 13 '24 10:05 cxwx