【问题标题】:How to handle unsolicited parameters in boost::program_options如何在 boost::program_options 中处理未经请求的参数
【发布时间】:2012-04-16 17:09:15
【问题描述】:

我使用boost::program_options 为我的应用程序提供命令行解析接口。我想配置它来解析选项,

using namespace boost::program_options;
options_description desc("Allowed options");
desc.add_options()
    ("help,h", "produce help message")
    ("version,v", "print the version number")
    ("include-path,I", value< vector<string> >(), "include path")
    ("input-file,i", value<string>(), "input file");

positional_options_description p;
p.add("input-file", 1);

variables_map vm;

parsed_options parsed = command_line_parser(ac, av).
options(desc).positional(p).run();
store(parsed, vm);
notify(vm);

我想对其进行配置,以便在最后一次切换之后的每个标记都以向量的形式返回。我已经尝试按照 Boost 文档中给出的示例使用 collect_unrecognized,但我遇到了一些问题,因为我也在为输入文件使用位置参数。

基本上我想这样做。如果我有:

./program -i "inputfile.abc" argument1 argument2 argument3

我希望它将inputfile.abc 存储在input-file 值中,并返回argument1argument2argument3 中的vector&lt;string&gt; 作为未经请求的参数。

然而,我也希望能够有一个位置参数,以便

./program "inputfile.abc" argument1 argument2 argument3

会给我同样的结果。

很抱歉,如果您已经提出此问题并感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    我想出了可以解决问题的代码,但这是一种轻微的解决方法。也就是说,我放弃了位置子句,并采取了无法识别的第一个论点。它似乎工作正常,但它不是很灵活。

    using namespace boost::program_options;
    
    options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "produce help message")
        ("version,v", "print the version number")
        ("include-path,I", value< vector<string> >(), "include path")
        ("input-file,i", value<string>(), "input file")
        ;
    
    variables_map vm;
    vector<string> additionalParameters;
    
    parsed_options parsed = command_line_parser(ac, av).
        options(desc).allow_unregistered().run();
    store(parsed, vm);
    additionalParameters = collect_unrecognized(parsed.options, 
        include_positional);
    notify(vm);
    
    if (!vm.count("input-file"))
        if (additionalParameters.empty()) 
        {
            cerr << "error: No input file specified\n";
            return EXIT_FAILURE;
        } 
        else
        {
            inputFileName = additionalParameters[0];
            additionalParameters.erase(additionalParameters.begin());
        }
    else
        inputFileName = vm["input-file"].as<string>();
    

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      相关资源
      最近更新 更多