如何使用Boost解析ini文件 [英] How to parse ini file with Boost

查看:43
本文介绍了如何使用Boost解析ini文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些示例值的 ini 文件,例如:

I have a ini file which contains some sample values like:

[Section1]
Value1 = 10
Value2 = a_text_string

我正在尝试加载这些值并使用 Boost 在我的应用程序中打印它们,但我不明白如何在 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.

我需要的时候只需要加载一个值,比如 string = 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.

可以用 Boost 做到这一点吗?

It is possible to do this with Boost?

目前,我正在使用此代码:

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;
   }

但这只是读取 for 循环中的所有值;相反,我只想在需要时读取单个值,而不需要在文件中插入值,因为它已经在我的程序中写入了我需要的所有值.

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;

这篇关于如何使用Boost解析ini文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆