nlohmann是一个流行的C++库,它提供了一个方便的JSON解析和操作接口。然而,它并不直接支持YAML格式的解析。如果你需要解析YAML格式的字符串,可以考虑使用其他专门针对YAML的库,如libyaml、yaml-cpp或者yaml-cpp03。
例如,使用yaml-cpp库可以解析YAML格式的字符串:
#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>
int main() {
std::string yamlString = R"(
key1: value1
key2: value2
key3:
- item1
- item2
- item3
)";
try {
YAML::Node config = YAML::Load(yamlString);
std::cout << "key1: " << config["key1"].as<std::string>() << std::endl;
std::cout << "key2: " << config["key2"].as<std::string>() << std::endl;
const YAML::Node& key3 = config["key3"];
for (const auto& item : key3) {
std::cout << "item: " << item.as<std::string>() << std::endl;
}
} catch (const YAML::Exception& e) {
std::cerr << "Failed to parse YAML: " << e.what() << std::endl;
}
return 0;
}
在上面的示例中,我们将一个包含YAML格式内容的字符串传递给YAML::Load函数进行解析,并通过节点访问方式获取键值对数据。请注意,在使用这些库之前,你需要确保已经正确安装和配置它们。
内容由零声教学AI助手提供,问题来源于学员提问




