【问题标题】:C++ boost::program_options reading arguments compatible with getopt_longC++ boost::program_options 读取与 getopt_long 兼容的参数
【发布时间】:2014-12-24 11:22:46
【问题描述】:

我正在对现有程序进行更新。 我正在用 boost::program_options 替换 Posix 的 getopt_long()。 但是我的工作并没有按我应该的那样工作:我想阅读以下论点:

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

我尝试了 boost::program_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 配置文件 有 boost::program_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

我在编辑后的问题是:如何处理使用 getopt_long 和 boost::program_options 的参数?

【问题讨论】:

  • 注意:getopt 是 POXIX,getopt_long 不是 POSIX,而是 GNU。不同的许可证 - getopt_long 是 GPL 的。

标签: c++ boost boost-program-options getopt-long


【解决方案1】:

如果您使用boost::program_options,则必须使用符号“=”才能正确解析参数。如果丢失,它将抛出异常。顺便说一句,boost::property_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;
}

“DEFAULT”是配置文件的部分名称。你可以试试看。

【讨论】:

  • 我猜这个答案是不相关的。这个问题显然是针对解析程序选项(posix getopt() 等)
猜你喜欢
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
相关资源
最近更新 更多