0

I am trying to create a config file for my application using yaml-cpp, I am able to create map by

    YAML::Emitter emitter;
    emitter << YAML::BeginMap;
    emitter << YAML::Key << "Autoplay" << YAML::Value << "false";
    emitter << YAML::EndMap;

    std::ofstream ofout(file);
    ofout << emitter.c_str();

which outputs something like,

var1: value1
var2: value2

But how would I make the top object like,

Foo:
  var1: value1
  var2: value2

Bar:
  var3: value3
  var4: value4

and so on.. How do I get the Foo and the Bar like in the above code.

1 Answer 1

1

What you want to achieve is a map containing two keys Foo and Bar. Each of these containing a map as a value. The code below show you how you can achieve that:

// gcc -o example example.cpp -lyaml-cpp
#include <yaml-cpp/yaml.h>
#include <fstream>

int main() {
  std::string file{"example.yaml"};

  YAML::Emitter emitter;
  emitter << YAML::BeginMap;

  emitter << YAML::Key << "Foo" << YAML::Value;
  emitter << YAML::BeginMap; // this map is the value associated with the key "Foo"
  emitter << YAML::Key << "var1" << YAML::Value << "value1";
  emitter << YAML::Key << "var2" << YAML::Value << "value2";
  emitter << YAML::EndMap;

  emitter << YAML::Key << "Bar" << YAML::Value;
  emitter << YAML::BeginMap; // This map is the value associated with the key "Bar"
  emitter << YAML::Key << "var3" << YAML::Value << "value3";
  emitter << YAML::Key << "var4" << YAML::Value << "value4";
  emitter << YAML::EndMap;

  emitter << YAML::EndMap; // This ends the map containing the keys "Foo" and "Bar"

  std::ofstream ofout(file);
  ofout << emitter.c_str();
  return 0;
}

You have to see these sorts of structures with a recursive mindset. This code will create the example you gave.

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

1 Comment

Nice, I didn't know it was this simple :D. 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.