Home > other >  yaml-cpp : How to read this yaml file content using c /Linux (using yaml-cpp version = 0.6.3 )
yaml-cpp : How to read this yaml file content using c /Linux (using yaml-cpp version = 0.6.3 )

Time:11-25

i am trying to read each Node and its respective content (yaml content is below) I am ending up with belwo error .

Error: terminate called after throwing an instance of 'YAML::TypedBadConversion

sample code :

#include <yaml-cpp/yaml.h>
YAML::Node config = YAML::LoadFile('yamlfile');
std::cout << config["Circles"]["x"].as<std::int64_t>();

Also i tried with some other approach but perhaps this yaml formt is complex one . I could read a sample format of yaml but not the one i have mentioned below .

Any helping hand ?

sample.yaml

- Pos: sensor - pos1
  Rectangle:
    - x: -0.2
      y: -0.13
      z: 3.26
    - x: 0.005
      y: -0.13
      z: 3.2
    - x: -0.2
      y: 0.10
      z: 3.26
    - x: 0.00
      y: 0.10
      z: 3.2

CodePudding user response:

The code in the question does not match the sample.yaml file you've provided but here's an example of how you could extract the floating points you have in the Rectangle in sample.yaml.

#include "yaml-cpp/yaml.h"

#include <iostream>

int main() {
    try {
        YAML::Node config = YAML::LoadFile("sample.yaml");

        // The outer element is an array
        for(auto dict : config) {
            // The array element is a map containing the Pos and Rectangle keys:
            auto name = dict["Pos"];
            std::cout << "Name: " << name << '\n';

            auto rect = dict["Rectangle"];

            // loop over the positions Rectangle and print them:
            for(auto pos : rect) {
                std::cout << pos["x"].as<double>() << ",\t"
                          << pos["y"].as<double>() << ",\t"
                          << pos["z"].as<double>() << '\n';
            }
        }

    } catch(const YAML::BadFile& e) {
        std::cerr << e.msg << std::endl;
        return 1;
    } catch(const YAML::ParserException& e) {
        std::cerr << e.msg << std::endl;
        return 1;
    }
}

Output:

Name: sensor - pos1
0.2,    -0.13,  3.26
0.005,  -0.13,  3.2
-0.2,   0.1,    3.26
0,      0.1,    3.2
  • Related