【问题标题】:Why does boost::program_options throw an error about a required argument when the default is defined为什么在定义默认值时 boost::program_options 会抛出有关所需参数的错误
【发布时间】:2016-02-25 02:20:28
【问题描述】:

这是我的代码:

#include <iostream>
#include <string>
#include "boost/program_options.hpp"
namespace po = boost::program_options;

int main(int argc, char *argv[]) {
    po::options_description cli_opts_desc("General flags");
    cli_opts_desc.add_options()
        ("help,h", po::value<std::string>()->default_value("all"), "Show this help message.")
    ;
    po::variables_map flags;
    po::store(po::parse_command_line(argc, argv, cli_opts_desc), flags);
    if (flags.count("help")) {
        std::cout << "flags['help'] is " << flags["help"].as<std::string>() << std::endl;
        if (flags["help"].as<std::string>() != "all") std::cout << "specific description for "
                                                              << flags["help"].as<std::string>() << std::endl;//todo
        else std::cout << cli_opts_desc << std::endl;
    } else {
        std::cout << "no --help provided" << std::endl;
    }
}

或者更确切地说,它的简化版本。当我跑步时

./test

它按预期显示帮助消息。但是,如果我运行

./test --help #or
./test -h

然后它会抛出一个错误:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::invalid_command_line_syntax> >'
  what():  the required argument for option '--help' is missing
Aborted

即使我声明了默认值,我也不明白为什么会发生这种情况。

是什么导致了这个错误?我该如何解决?

注意:如果可能,我想避免使用implicit_value;在现实世界中,这不仅限于我的--help,并且能够为短选项指定参数并在它们之间有一个空格是避免愚蠢错误的好小东西。

【问题讨论】:

  • "default_value" 表示仅当您不使用此选项时才使用默认值(例如纯 './test')。但是,如果您使用此选项('-h'),则必须将默认值添加到命令行(例如,'./test -h foo')。这就是 boost 的 program_options 的工作原理。换句话说:这种行为是有意的。

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


【解决方案1】:

试试这个:

("help,h", "Show this help message.")

无参数,但不提供参数时无投诉。

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多