How to read config.yaml file using C++?

Viewed 78

I want to read a config.yaml file using C++.

My Simple code:

#include <typeinfo>

#include <ryml_std.hpp>
#include <ryml.hpp>


std::string get_file_contents(const char* filename)
{
    std::ifstream in(filename, std::ios::in | std::ios::binary);
    if (!in) {
        std::cerr << "could not open " << filename << std::endl;
        exit(1);
    }
    std::ostringstream contents;
    contents << in.rdbuf();
    //std::cout << contents.str() << std::endl;
    return contents.str();
}

int main(int argc, char const* argv[])
{
    try {
        std::string contents = get_file_contents("C:/yaml/config.yaml"); 
        ryml::Tree tree = (ryml::parse(ryml::to_csubstr(contents)));
     
     std::vector<float> data;
     tree[0] >> data; ***I am failing here***
     tree[3] >> width;

    }
   catch(std::exception &e){
       std::cout << e.what() <<std::endl;
     }
}

How can I read the key-value pairs in the YAML file below.

I am using metric inside YAML. If metrics in the yaml and how we can convert to c++ vector.

My config.yaml

dist2:
- - 0.045533736417839546
  - 0.16564066086021373
  - 0.028658520327566304
  - 0.009133486414620372
  - -0.5801749091384203
height: 480
rms: 1.6671979326607804
width: 640
R:
- - 0.986119137868725
  - 0.04723012789836373
  - -0.15918027813691865
- - -0.07869384510750799
  - 0.9771216529170358
  - -0.19758682684550466
- - 0.1462064453819944
  - 0.2073706594949828
  - 0.9672750823366525
1 Answers

Hi as far as I understood there is misuse on usage of API. You should pass the map name string into tree function :

        int main(int argc, char const* argv[])
    {
        try {
            std::string contents = get_file_contents("C:/yaml/config.yaml"); 
            ryml::Tree tree = (ryml::parse(ryml::to_csubstr(contents)));         
            CHECK(tree["dist2"].[0].val() >> data);
            CHECK(tree["width"].val() >> width);

        }
       catch(std::exception &e){
           std::cout << e.what() <<std::endl;
         }
    }
    

You may find reference in here

Related