yaml-cpp库

作用

下载安装yaml-cpp库

sudo apt install libyaml-cpp-dev

CMakeLists.txt配置yaml-cpp依赖

cmake_minimum_required(VERSION 3.9.0)
project(pro_judge_path)

# set(path_to_third_party "${CMAKE_SOURCE_DIR}/third_party")
find_package(yaml-cpp REQUIRED)
if(NOT yaml-cpp_FOUND)
  message("Not found yaml-cpp library")
endif()

set(CMAKE_CXX_STANDARD 20)

add_executable(exec_file yaml_create_file.cpp)
target_link_libraries(exec_file yaml-cpp)

引用头文件

#include <yaml-cpp/yaml.h>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YAML是一种人类可读的数据序列化格式,它非常适用于配置文件和数据交换。yaml-cpp是一个C++,用于解析和生成YAML格式的数据。 以下是yaml-cpp的使用示例: 1. 安装yaml-cpp 首先,需要安装yaml-cpp。可以使用以下命令在Ubuntu上安装: ``` sudo apt-get install libyaml-cpp-dev ``` 2. 解析YAML文件 假设有一个名为config.yamlYAML文件,其内容如下: ``` name: John Smith age: 30 address: street: 123 Main St. city: Anytown state: CA zip: 12345 ``` 可以使用以下代码解析该文件: ```c++ #include <yaml-cpp/yaml.h> #include <iostream> int main(int argc, char** argv) { YAML::Node config = YAML::LoadFile("config.yaml"); std::string name = config["name"].as<std::string>(); int age = config["age"].as<int>(); std::string street = config["address"]["street"].as<std::string>(); std::string city = config["address"]["city"].as<std::string>(); std::string state = config["address"]["state"].as<std::string>(); int zip = config["address"]["zip"].as<int>(); std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; std::cout << "Address: " << street << ", " << city << ", " << state << " " << zip << std::endl; return 0; } ``` 输出结果为: ``` Name: John Smith Age: 30 Address: 123 Main St., Anytown, CA 12345 ``` 3. 生成YAML文件 可以使用以下代码生成一个YAML文件: ```c++ #include <yaml-cpp/yaml.h> #include <iostream> #include <fstream> int main(int argc, char** argv) { YAML::Emitter out; out << YAML::BeginMap; out << YAML::Key << "name" << YAML::Value << "John Smith"; out << YAML::Key << "age" << YAML::Value << 30; out << YAML::Key << "address"; out << YAML::BeginMap; out << YAML::Key << "street" << YAML::Value << "123 Main St."; out << YAML::Key << "city" << YAML::Value << "Anytown"; out << YAML::Key << "state" << YAML::Value << "CA"; out << YAML::Key << "zip" << YAML::Value << 12345; out << YAML::EndMap; out << YAML::EndMap; std::ofstream fout("config.yaml"); fout << out.c_str(); return 0; } ``` 该代码将生成一个名为config.yaml的文件,其内容与上述示例相同。 总结 yaml-cpp是一个非常方便的C++,用于解析和生成YAML格式的数据。在使用时,只需包含头文件,并调用相应的函数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值