C++使用yaml-cpp解析yaml文件的方式

复制
#include <yaml-cpp/yaml.h>
#include <string>
using namespace std;
int main() {
std::string file_path;
// 读取yaml文件
YAML::Node yaml_node = YAML::LoadFile(file_path);
// 读取yaml字符串
std::string yaml_content;
yaml_node = YAML::Load(yaml_content);
// 读取文件中,a对应的内容
YAML::Node yaml_node_a = yaml_node["a"];
// 判断文件中是否存在a这个key
if (yaml_node_a != nullptr) {
// exist
} else {
// not exist
}
// 读取文件中,a中的b对应的内容
YAML::Node yaml_node_a_b = yaml_node["a"]["b"];
// 假设a是string的解析方式
string str_a = yaml_node_a.as<string>();
// 假设a是int的解析方式
int int_a = yaml_node_a.as<int>();
// 判断a是否是一个map
bool is_map = yaml_node_a.IsMap();
// 假设a是map时的遍历方式
for (auto it = yaml_node_a.begin(); it != yaml_node_a.end(); ++it) {
// 获取key
std::string key = it->first.as<string>();
// 获取value,假设value还是YAML::Node
YAML::Node value = it->second;
// 对value进一步处理
}
// 判断a是否是一个数组
bool is_seq = yaml_node_a.IsSequence();
// a中元素的个数
int size = yaml_node_a.size();
// 假设a是数组时的遍历方式
for (int i = 0; i < size; ++i) {
// 假设数组内部是string
std::string value = yaml_node_a[i].as<string>();
}
return 0;
}
posted @   umichan  阅读(4229)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示