1

Initial Question

I have a config.yaml that has structure similar to

some_other_key: 34

a:
  b:
    c:
      d: 3

I thought I could do

YAML::Node config = YAML::LoadFile(config_filename.c_str());
int x  = config["a"]["b"]["c"]["d"].as<int>();

but I get

terminate called after throwing an instance of
'YAML::TypedBadConversion<int>' 
what():  bad conversion

How do I descend through my config.yaml to extract a value like this? I also get that same exception if I mistype one of the keys in the path, so I can't tell from the error if I am accidentally working with a null node or if there is a problem converting a valid node's value to int

Follow up After First Replies

Thank you for replying! Maybe it is an issue with what is in the config.yaml? Here is a small example to reproduce,

yaml file: config2.yaml

daq_writer:
  num: 3
  num_per_host: 3
  hosts:
    - local
  datasets:
    small:
      chunksize: 600

Python can read it:

Incidentally, I am on linux on rhel7, but from a python 3.6 environment, everything looks good:

$ python -c "import yaml; print(yaml.load(open('config2.yaml','r')))"
{'daq_writer': {'num_per_host': 3, 'num': 3, 'datasets': {'small': {'chunksize': 600}}, 'hosts': ['local']}}

C++ yaml-cpp code

The file yamlex.cpp:

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

int main() {
  YAML::Node config = YAML::LoadFile("config2.yaml");
  int small_chunksize = config["daq_writer"]["datasets"]["smal"]["chunksize"].as<int>();
}

When I compile and run this, I get:

(lc2) psanagpu101: ~/rel/lc2-hdf5-110 $ c++ --std=c++11 -Iinclude -Llib -lyaml-cpp yamlex.cpp
(lc2) psanagpu101: ~/rel/lc2-hdf5-110 $ LD_LIBRARY_PATH=lib ./a.out
terminate called after throwing an instance of 'YAML::TypedBadConversion<int>'
  what():  bad conversion
Aborted (core dumped)
(lc2) psanagpu101: ~/rel/lc2-hdf5-110 $ gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

I have been able to read top level keys, like the some_other_key that I referenced above, but I got an error when I went after this nested key. Good to know that syntax works!

3
  • Can you post a full working (failing) example? In the answer below I tried what you're doing, and it seems to pass. Commented Feb 17, 2017 at 15:09
  • Thanks, updated question with full example Commented Feb 17, 2017 at 16:31
  • Thanks; updated answer. Commented Feb 17, 2017 at 19:51

1 Answer 1

1

You have a typo in your keys: instead of "small", you wrote "smal".

Sign up to request clarification or add additional context in comments.

1 Comment

oh geez! Sorry to take your time on this, I was looking really hard for a typo but not hard enough! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.