用C++ 读取yaml文件 # 这是一个包含中文字符的YAML文件示例 信息: 姓名: 张三 年龄: 25 地址: 上海市 职业: 工程师的代码
时间: 2024-04-13 20:27:55 浏览: 9
在C++中读取YAML文件可以使用第三方库,如yaml-cpp。下面是一个使用yaml-cpp库读取上述示例中的YAML文件的示例代码:
首先,确保你已经安装了yaml-cpp库。你可以从https://github.com/jbeder/yaml-cpp下载源代码并进行编译安装。
接下来,你可以使用以下C++代码来读取YAML文件并提取相应的信息:
```cpp
#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>
int main() {
// 读取YAML文件
YAML::Node yaml_data = YAML::LoadFile("path/to/your/file.yaml");
// 提取信息
std::string name = yaml_data["信息"]["姓名"].as<std::string>();
int age = yaml_data["信息"]["年龄"].as<int>();
std::string address = yaml_data["信息"]["地址"].as<std::string>();
std::string occupation = yaml_data["信息"]["职业"].as<std::string>();
// 打印提取的信息
std::cout << "姓名: " << name << std::endl;
std::cout << "年龄: " << age << std::endl;
std::cout << "地址: " << address << std::endl;
std::cout << "职业: " << occupation << std::endl;
return 0;
}
```
将上述代码中的`"path/to/your/file.yaml"`替换为你的YAML文件的实际路径。运行代码后,将输出提取到的姓名、年龄、地址和职业信息。
请确保在编译时链接了yaml-cpp库,并设置了正确的include路径。具体的编译命令可以根据你的编译环境和yaml-cpp库安装方式进行调整。
希望以上代码对你有帮助!