【问题标题】:Unable to read INI file Parsing using boost::program_options无法使用 boost::program_options 读取 INI 文件解析
【发布时间】:2011-11-15 10:26:41
【问题描述】:

我是 C++ 和 boost 的新手。我正在尝试使用 boost::program_options 读取(稍后写入)INI 文件。我什至尝试使用 boost::property_tree。

当使用 std::stringstream s("[test]\n""a=2\n""b=3\n") 时,两者(program_options & property_tree) 都能完美工作,但在使用 std::ifstream 时则不行s(“维度.ini”)。我已将文件:Dimension.ini、Rcasdim.hpp/cpp 放在同一个文件夹中,并且在搜索目录中也有相关的 boost lib 文件。

INI File

[Section]

a=2

b=3

Purpose:  
I need to dynamically set the "Value" (at the start ONLY) for a Particular "Key" in INI file & Later USE that Previously set "Value" for that "Key" by other project files (more, as a toggle)

 #include boost/program_options/detail/config_file.hpp

 #include boost/program_options/parsers.hpp


namespace pod = boost::program_options::detail;

class CRcasdim
{
    public:
    CRcasdim(){};
    ~CRcasdim(){};
    std::string getrcasdim(float);

    private:
    std::string sd;
};

std::string CRcasdim::getrcasdim(float d)

{

    //std::stringstream s("[Section]\n""a=2\n""b=3\n"); WORKS

    std::ifstream s("dimension.ini"); DOESNT WORK

    if(!s)
    {
        std::cerr<<"error"<<std::endl;
    }

    std::set<std::string> options;
    std::map<std::string, std::string> parameters;

    options.insert("Section.a");
    options.insert("Section.b");

try

{

    for (pod::config_file_iterator i(s, options), e ; i != e; ++i)

        parameters[i->string_key] = i->value[0];   
}

catch(std::exception& e)

{
std::cerr<<"Exception: ";
}

    if (d==2)
    sd = parameters["Section.a"];

    else if (d==3)
    sd = parameters["Section.b"];

    return sd;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    您不需要将 ini 文件和 hpp/cpp 文件放在同一个文件夹中。
    dimension.ini 文件与您的二进制文件位于同一文件夹中(在 Windows 上可在 linux 上执行 .exe)。
    该位置取决于您的构建系统和平台,而且很可能有些我忘记了。

    【讨论】:

    • thnx 回复..为什么 boost::program_options 无法在我的程序中从“dimension.ini”读取/检测“Key=Value”?错误在哪里?
    • std::ifstream s("dimension.ini") 这一行表示从当前工作目录加载文件 dimensions.ini。您需要指定您的路径或在运行时确定它。它与boost无关。
    • 问题在于传递文件名。文件名(文件)应该在property_tree 控制程序之前就可以打开了。简单来说,对于这个“文件”,做“这个”(这里是INI文件的property_tree解析)
    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多