YAML-CPP

Posted by Bryan on August 26, 2018

安装

Method 1: github网站下载,编译成库文件
Method 2: 安装ros后就安装了yaml-cpp

读yaml文件

#include <iostream>
#include <fstream>
#include <string>
#include "yaml-cpp/yaml.h"
template<typename T>
void operator >> (const YAML::Node& node, T& i)  //最新的yaml-cpp 0.5取消了运算符">>",但是还是会有好多的旧代码
{
  i = node.as<T>();                              //依旧在使用,所以重载下">>"运算符
}
void configure(const YAML::Node& node);
void nodePrint(const YAML::Node& node);
int main()
{
  YAML::Node config = YAML::LoadFile("../monsters.yaml");  
  configure(config["Ladybug"]);
  return 0;
}
void configure(const YAML::Node& node)
{
  std::cout << "node size is " << node.size() << std::endl;
  for (unsigned int i = 0; i < node.size(); i++)
  {
    nodePrint(node[i]);
  }
}
void nodePrint(const YAML::Node& node)
{
  int name;
  int topic;
  string timeout;
  double priority;
  node["showImage"]       >> name;
  node["saveImage"]      >> topic;
  node["savePath"]    >> timeout;
  node["resize"]   >> priority;
}

yaml文件

# yaml for ladybug and rcs
Ladybug:
  - showImage:   1
    saveImage:   1
    savePath:    "../filename"
    resize:      1.0
    truncateBottom:    0.1
    truncateTop:    0.1
DetectArea:
  - radius:      6.0
    speed:       2.0

写yaml文件

YAML::Emitter out;
out << YAML::BeginSeq;
out << "eggs";
out << "bread";
out << "milk";
out << YAML::EndSeq;

结果:

- eggs
- bread
- milk

=========================

YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "name";
out << YAML::Value << "Ryan Braun";
out << YAML::Key << "position";
out << YAML::Value << "LF";
out << YAML::EndMap;

结果:

name: Ryan Braun
position: LF

=========================

YAML::Emitter out;
out << YAML::BeginMap;
out << YAML::Key << "name";
out << YAML::Value << "Barack Obama";
out << YAML::Key << "children";
out << YAML::Value << YAML::BeginSeq << "Sasha" << "Malia" << YAML::EndSeq;
out << YAML::EndMap;

结果:

name: Barack Obama
children:
  - Sasha
  - Malia

==========================