问题描述
我有一个包含像一些样本值的ini文件:
I have a ini file which contains some sample values like:
[Section1]
Value1 = 10
Value2 = a_text_string
我试图加载这些价值观和我与升压应用程序进行打印,但我不知道如何做到这一点的C ++。
I'm trying to load these values and print them in my application with Boost but I don't understand how to do this in C++.
我搜索在这个论坛,以便找到一些例子(我一直用C等,我不是在C非常好++),但我只发现了有关如何从文件中的所有一次读取值的例子。
I searched in this forum in order to find some examples (I always used C and so I'm not very good in C++) but I found only examples about how to read values from file all at once.
我需要加载只是当我想,一个值如字符串= Section1.Value2
,因为我并不需要阅读所有的值,但只是少数它们。
I need to load just a single value when I want, like string = Section1.Value2
because I don't need to read all the values, but just few of them.
我想加载单个值并将它们存储在变量才能使用它们时,我想在我的应用程序。
I'd like to load single values and to store them in variable in order to use them when I want in my application.
这是可能的升压做到这一点?
It is possible to do this with Boost?
目前,我使用这个code:
At the moment, I'm using this code:
#include <iostream>
#include <string>
#include <set>
#include <sstream>
#include <exception>
#include <fstream>
#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
namespace pod = boost::program_options::detail;
int main()
{
std::ifstream s("file.ini");
if(!s)
{
std::cerr<<"error"<<std::endl;
return 1;
}
std::set<std::string> options;
options.insert("Test.a");
options.insert("Test.b");
options.insert("Test.c");
for (boost::program_options::detail::config_file_iterator i(s, options), e ; i != e; ++i)
std::cout << i->value[0] << std::endl;
}
但是,这只是读了为
循环中的所有值;在相反的我只是想,当我想读一个价值观和我不需要在文件中插入值,因为它已经与我需要在我的程序中的所有值写入。
But this just read all the values in a for
loop; at the contrary I just want to read single values when I want and I don't need to insert values in the file, because it is already written with all the values which I need in my program.
推荐答案
您也可以使用Boost.PropertyTree读取.ini文件:
You can also use Boost.PropertyTree to read .ini files:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
...
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config.ini", pt);
std::cout << pt.get<std::string>("Section1.Value1") << std::endl;
std::cout << pt.get<std::string>("Section1.Value2") << std::endl;
这篇关于如何解析与升压ini文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!