【发布时间】:2020-08-29 09:40:50
【问题描述】:
这是一个使用 boost 来解析选项的简单程序:
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char **argv)
{
try
{
size_t param = std::numeric_limits<size_t>::max();
po::options_description desc("Syntax: [options] \"input binary file\".\nAllowed options:");
desc.add_options()
("help,h", "produce help message")
("param,p", po::value<size_t>(¶m), "param");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
}
else
{
std::cout << "Running with param " << param << std::endl;
return 0;
}
}
catch(std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
}
catch(...) {
std::cerr << "Exception of unknown type!\n";
}
return 1;
}
这里是产生的输出:
-
hex2txt.exe输出Running with param 0 -
hex2txt.exe --param 3输出Running with param 3 -
hex2txt.exe --toto输出error: unrecognised option '--toto'
不过,这一切都是意料之中的:
hex2txt.exe foo 输出Running with param 0
我本来希望得到一个错误,因为“foo”不是预期的。我在这里做错了什么?
【问题讨论】:
-
您的代码有两个相互竞争的命令行解析运行 + 存储。这是多余的,并且可能会产生令人惊讶的效果(我没有想到一个例子)。
标签: c++ boost boost-program-options