如何使用 yaml-cpp 读取此 YAML 文件:
sensors:
- id: 5
hardwareId: 28-000005a32133
type: 1
- id: 6
hardwareId: 28-000005a32132
type: 4
Run Code Online (Sandbox Code Playgroud)
我不明白我如何获得sensors物品,使用它。
据我了解sensors是一个YAML::Node. 我怎么才能得到它?
更新 1:
YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& node_test1 = confg["sensors"];
for (std::size_t i = 0; i < node_test1.size(); i++) {
const YAML::Node& node_test2 = node_test1[i];
std::cout << "Id: " << node_test2["id"].as<std::string>() << std::endl;
std::cout << "hardwareId: " << node_test2["hardwareId"].as<std::string>() << std::endl << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
此代码有效,但它是使用有关旧 api 的教程编写的。我认为这段代码可以用迭代器重写,但我现在不知道如何重写。
看起来你的代码有效,但如果你想用迭代器重写它,你可以:
YAML::Node config = YAML::LoadFile(config_path);
const YAML::Node& sensors = config["sensors"];
for (YAML::iterator it = sensors.begin(); it != sensors.end(); ++it) {
const YAML::Node& sensor = *it;
std::cout << "Id: " << sensor["id"].as<std::string>() << "\n";
std::cout << "hardwareId: " << sensor["hardwareId"].as<std::string>() << "\n\n";
}
Run Code Online (Sandbox Code Playgroud)