C++ boost::p rogram_options 读取与getopt_long兼容的参数

C++ boost::program_options reading arguments compatible with getopt_long

本文关键字:long 参数 getopt 读取 boost rogram options C++      更新时间:2023-10-16

我正在现有程序中开发更新。我正在用boost::p rogram_options替换Posix的getopt_long()。但是我的工作没有发挥应有的作用:我想阅读以下论点:

-server=www.example.com
-c config.txt

我尝试了 boost::p rogram_options::command_line_style 的许多可能性,但我找不到可以给出等于 getopt_long 行为的组合。

我发现对于参数:

-server=www.example.com

我需要标志:

command_line_style::allow_long_disguise | command_line_style::long_allow_adjacent

但我在以下方面有创始标志的问题:

-c config.txt

我发现标志:

command_line_style::allow_short | command_line_style::allow_dash_for_short | command_line_style::short_allow_next

几乎给我我想要的。几乎是因为:

ProgramOptionsParserTest.cpp:107: Failure
Value of: params.config
  Actual: " config.txt"
Expected: expectedParams.config
Which is: "config.txt"

所以在使用 boost::algorithm::trim() 之后,它将是我想要的。

所以我的问题是:是否有可能处理这样的论点-c 配置.txtwith boost::p rogram_options 但没有 boost::algorithm::trim()?

编辑我注意到上面的标志不适用于未注册的参数。我已注册选项:

  programOptionsDescription.add_options()
      ("help,h", "display help message")
      ("config,c", value<std::string>(), "use configfile")
      ("server,s", value<std::string>(), "server")
      ("ipport,p", value<uint16_t>(), "server port");

但是当我使用未注册的选项时(是的,我有 basic_command_line_parser::allow_unregistered()):

-calibration=something

明白了:

the argument ('alibration=something') for option '-config' is invalid

我版后的问题是:如何处理使用 boost::p rogram_options 处理getopt_long的参数?

如果使用 boost::p rogram_options,符号 '=' 是正确解析参数所必需的。如果缺少,它将引发异常。顺便说一下,boost::p roperty_tree 也是解析配置文件的一个非常好的选择。法典:

#include <iostream>
#include <boost/propery_tree.hpp>
#include <boost/propery_tree/ini_parse.hpp>
int main()
{
    string filename("test.conf");
    boost::property_tree::ptree parser;
    boost::property_tree::ini_parser::read_ini(filename, parser);
    const string param_1 = parser.get<string>("DEFAULT.-server");
    const string param_2 = parser.get<string>("DEFAULT.-c");
    cout << param_1 << ' ' << param_2 << endl;
    return 0;
}

"默认"是配置文件的部分名称。你可以试试。