【问题标题】:Is this kind of repeatable options possible with boost::program_options?boost::program_options 是否可以实现这种可重复的选项?
【发布时间】:2016-05-01 23:24:46
【问题描述】:

我有需要特殊处理的选项--foo(缩写-f)和--bar,它们是可重复的,并且顺序很重要。因此,对于以下内容:

program --foo 1 --z -f 2 --bar 3 --x --foo 4

我想设置一个能够构造 [("foo", 1), ("foo", 2), ("bar", 3), ("foo", 4)] 的键值映射。

请注意这个元组数组的顺序,和命令行中的顺序是一样的。我已经丢弃了数组中不重要的选项,但它们可能仍然存在于命令行中。

似乎使用boost::program_options 允许可重复选项的唯一方法是为任何给定选项调用composing(),但是由于每个选项都将其所有值存储在一个向量中,我失去了交错选项所需的顺序。

那么,boost::program_options 可以帮忙吗?

编辑

我已在此处询问替代软件建议:https://softwarerecs.stackexchange.com/questions/31766/

并使用 Poco 回答。

【问题讨论】:

  • 你能接受--foo=1 --foo=2吗?
  • @RichardHodges 是的,我插入了--z 以证明它可能没有严格的顺序并且可以互换。如果您的意思是限制请求以受约束的方式接受它,那将无视问题。
  • @RichardHodges 如果您知道一个替代的小型命令行解析器库也可以轻松完成此操作,我将不胜感激。

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


【解决方案1】:

假设您可以接受必须在 --foo 和值之间放置等号,这可能会满足您的需求:

#include <iostream>
#include <boost/program_options.hpp>
#include <vector>
#include <iterator>
#include <algorithm>

int main(int argc, const char**argv)
{
    std::vector<int> foos;
    boost::program_options::options_description desc("Command Line Options");
    desc.add_options()
    ("foo,F", boost::program_options::value(&foos)->multitoken(), "integers for foo");


    std::cout << desc << std::endl;

    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
    boost::program_options::notify(vm);

    std::copy(foos.begin(), foos.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    return 0;
}

用命令行调用:

./a.out --foo=1 --foo=2

产量:

Command Line Options:
  -F [ --foo ] arg      integers for foo

1, 2,

【讨论】:

  • 对不起,这没有帮助。在问题中,--foo--bar 都很重要。
  • 啊,我明白了。那么也许你想直接使用linuxgetopt
  • @pepper_chico 文档在这里:man7.org/linux/man-pages/man3/getopt.3.html
  • 可能。我不熟悉它,而且,我不希望得到 C-low-level-like ...谢谢
  • @pepper_chico 如果将 argv 转换为 std::strings,手动解析它们非常简单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 2020-05-19
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
相关资源
最近更新 更多