我有一个包含一些样本值就像一个ini文件:我试图加载这些值,并在我与升压应用程序进行打印如何解析ini文件与升压
[Section1]
Value1 = 10
Value2 = a_text_string
但我不了解如何在C++中执行此操作。我在这个论坛搜索,以找到一些例子(我总是使用C,所以我不是很好的C++),但我只找到了关于如何从文件一次读取值的例子。
我需要加载一个单一的值,比如string = Section1.Value2
,因为我不需要读取所有的值,但只是其中的一小部分。
我想加载单个值并将它们存储在变量中,以便在我的应用程序中使用它们。
可以用Boost做到这一点吗?
目前,我正在使用此代码:
#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;
}
但这只是读入for
循环中的所有值;相反,我只想在需要时读取单个值,并且不需要在文件中插入值,因为它已经写入了我在程序中需要的所有值。
很好的答案! 这是我需要我的应用程序。 真的非常感谢! – 2011-05-30 12:55:23
如果我不知道某些可用键的集合,但我仍想获取键=值对的完整列表,该怎么办?即你将如何重写你的程序而不使用“Section1.Value1”和“Section1.Value2”常量? – javapowered 2013-04-21 19:02:15
更新:我发现这个问题http://stackoverflow.com/questions/11065938/boost-program-options-get-all-entries-in-section根据它是不可能的,没有编写自定义代码... – javapowered 2013-04-21 19:08:17