如何建網(wǎng)站費用多少武漢seo網(wǎng)站排名
在日常的代碼中,有一些值是配置文件中定義的,這些值可以根據(jù)用戶的要求進行調(diào)整和改變。這往往會寫在yaml格式的文件中。這樣開放程序給用戶時,就可以不必開放對應(yīng)的源碼,只開放yaml格式的配置文件即可。
將配置文件中的值讀入程序也非常的簡單。
我們先寫一個簡單的配置文件,然后將其中的值讀入到程序中。配置文件如下:
general_test:test_name: yaml_testis_debug: truefile_path: ./int_value:test_time: 2
需要注意的是,這里面變量的值在讀入程序之初是沒有類型的。但是讀入之后,其實是有對應(yīng)需要的類型的,比如is_debug讀入后需要時bool類型,test_time讀入之后需要是int類型。
下面寫個C++程序,做讀入上面配置文件的簡單驗證。
首先需要引用頭文件
#include <yaml-cpp/yaml.h>
有幾個需要注意的地方:
1. yaml文件是分級寫入的,在C++程序中也需要分級讀取,或者看成總節(jié)點和子節(jié)點的關(guān)系。如程序中config表示總文件節(jié)點,要讀取第二級的test_name就需要進行兩層的穿透。另外,上面提到的類型問題,在這里用.as來體現(xiàn),將對應(yīng)的配置文件中的值,讀入成程序中期望得到的值的類型,這里test_name希望讀入為string。
config["general_test"]["test_name"].as<std::string>()
2. 層級過多的時候,防止一行輸入過多??梢远x子節(jié)點名稱,然后從子節(jié)點開始尋值。
YAML::Node subnode = config["general_test"];const bool is_debug = subnode["is_debug"].as<bool>();const int test_time = subnode["int_value"]["test_time"].as<int>();
完整的代碼如下:
#include <iostream>
#include <yaml-cpp/yaml.h>int main()
{std::string file = "yaml_test.yaml";// 使用loadfile加載要讀取的配置文件路徑Y(jié)AML::Node config = YAML::LoadFile(file);// 通過如下格式,獲取配置文件中對應(yīng)項的值const std::string name = config["general_test"]["test_name"].as<std::string>();// 配置文件分級較多時,可以設(shè)置子節(jié)點 YAML::Node subnode = config["general_test"];const bool is_debug = subnode["is_debug"].as<bool>();const int test_time = subnode["int_value"]["test_time"].as<int>();std::cout << "test name is: " << name << std::endl;std::cout << "is_debug is: " << is_debug << std::endl;std::cout << "test time is: " << test_time << std::endl;return 0;
}
最后,在編譯的時候注意需要帶上yaml的庫
g++ yaml_test.cpp -lyaml-cpp
運行結(jié)果如下:
test name is: yaml_test
is_debug is: 1
test time is: 2