Linux环境下,yaml文件读写

1、完整代码

重要事情说三遍: 注意: 要用YAML::LoadFile(),不要用YAML::Load()
重要事情说三遍: 注意: 要用YAML::LoadFile(),不要用YAML::Load()
重要事情说三遍: 注意: 要用YAML::LoadFile(),不要用YAML::Load()

否则,会报如下错误:terminate called after throwing an instance of ‘YAML::BadSubscript’

在这里插入图片描述

#include "yaml-cpp/yaml.h"

int main()
{
    std::string strFuncSuffix = "main()";

    YAML::Node yamlNodeConfig;// = YAML::LoadFile(");
    std::string strConfigFullFileName = "~/Config/Test.yaml";
    if( access(strConfigFullFileName.c_str(), F_OK ) == -1 )
    {//not exist
        std::ofstream ofsConfigFile(strConfigFullFileName.c_str());
        yamlNodeConfig["value1"] = "31.6317707667"; //latitude
        yamlNodeConfig["value2"] = "118.554674727"; //longitude
        yamlNodeConfig["value3"] = "0.2"; //grid area width
        yamlNodeConfig["value4"] = "0.2"; //grid area width
//        yamlNodeConfig[""] = "";
//        yamlNodeConfig[""] = "";
        ofsConfigFile << yamlNodeConfig;   //写文件
        ofsConfigFile.close();
    }

    if( access(strConfigFullFileName.c_str(), F_OK ) == -1 ) {//not exist
        std::cout<< "the config file not exist. exit now" << std::endl;
        return 0;
    }


  //Load Config
    yamlNodeConfig = YAML::LoadFile(strConfigFullFileName);
    std::double_t value1 = yamlNodeConfig["value1"].as<std::double_t>();   //latitude
    std::double_t value2 = yamlNodeConfig["value2"].as<std::double_t>(); //longitude
    std::double_t value3= yamlNodeConfig["value3"].as<std::double_t>();   //latitude
    std::double_t value4 = yamlNodeConfig["value4"].as<std::double_t>(); //longitude

    std::cout << value1 << std::endl;
    std::cout << value2 << std::endl;
    std::cout << value3 << std::endl;
    std::cout << value4 << std::endl;

}
Logo

更多推荐