这是我的代码:
#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
,并且能够为短选项指定带有空格的参数是一件很好的小事,可以避免愚蠢的错误。
最佳答案
试试这个:
("help,h", "Show this help message.")
没有参数,但没有提供参数时没有提示。
关于c++ - 为什么在定义默认值时 boost::program_options 抛出有关必需参数的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617045/