2015-07-01 38 views
0

我正在使用boost :: property_tree來讀取.ini文件。Boost :: ini_parser:讀取特定部分值的方法是什麼?

我知道我可以閱讀特定key(inside section) -> iniTree.get<std::string>("section.key")

我知道我可以讀取ini文件中的所有值。

我想只讀取特定部分的密鑰。

類似的東西:iniTree.get<std::vector<std::string> >("section")

可能嗎?

+0

[好的。有時間說出來。我認爲#Boost PropertyTree是一件奇怪的事情。 (https://twitter.com/sehetw/status/556793518946258945) – sehe

回答

1

是的。您使用'get_child'來獲取子樹。

您可以在使用的情況下,你get_child_optional不事先知道該部分是否存在。

這裏有一個演示,同時顯示變化:

Live On Coliru

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/ini_parser.hpp> 
#include <fstream> 
#include <iostream> 

using boost::property_tree::ptree; 

int main() { 

    std::fstream ifs("input.txt"); 
    ptree pt; 

    read_ini(ifs, pt); 

    // let's get just the section2 

    if (boost::optional<ptree&> oops = pt.get_child_optional("oops")) { 
     std::cout << "There is a section `oops`\n"; 
    } else { 
     std::cout << "There is NO section `oops`\n"; 
    } 

    ptree& sub1 = pt.get_child("section2"); // we want the CCs! 
    write_ini(std::cout, sub1); 
} 

並給予input.txt中的:

[section1] 

huh=value1 
slam=value2 
cram=value3 

[section2] 

rabbits=creditcard1 
die=creditcard2 
eagerly=creditcard3 

它會打印輸出:

There is NO section `oops` 
rabbits=creditcard1 
die=creditcard2 
eagerly=creditcard3 
+0

如果您有興趣,請點擊[live-stream](https:// www .livecoding.tv/video/boost-property-tree-and-geometry-intersection /)回答這個問題。 ([實驗](http://chat.stackoverflow.com/transcript/10?m=24182469#24182469)) – sehe

+0

剛剛意識到,我從未列舉該部分中的值。這裏你去:http://coliru.stacked-crooked.com/a/c1395078691c8d67 – sehe

相關問題