【问题标题】:Command line parser ignores required option命令行解析器忽略必需的选项
【发布时间】:2016-07-05 03:12:25
【问题描述】:

给定以下程序

#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>

using namespace std;
namespace po = boost::program_options;

int main(int argc, const char *argv[]) {
    try {
        po::options_description global("Global options");
        global.add_options()
            ("x", po::value<int>()->required(), "The required x value");

        po::variables_map args;
        // shouldn't this throw an exception, when --x is not given?
        po::store(po::parse_command_line(argc, argv, global), args);

        // throws bad_any_cast
        cout << "x=" << args["x"].as<int>() << endl;
    } catch (const po::error& e) {
        std::cerr << e.what() << endl;
    }

    cin.ignore();
    return 0;
}

X 是必需的,但给定一个空的命令行 parse_command_line 不会引发异常。因此,当我通过args["x"] 访问x 时,它会崩溃。我得到了bad_any_cast

【问题讨论】:

    标签: c++ boost command-line-arguments


    【解决方案1】:

    调用boost::program_options::store,顾名思义,仅将来自第一个参数(即boost::program_options::basic_parsed_options)的选项存储在作为第二个参数传递的映射中。要运行所需的检查并获得您期望的异常,您还必须显式调用 boost::program_options::notify

    po::store(po::parse_command_line(argc, argv, global), args);
    po::notify(args);
    

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 1970-01-01
      • 2012-05-25
      • 2013-05-16
      • 2015-01-15
      • 2015-02-28
      • 2019-08-26
      • 1970-01-01
      • 2022-10-05
      相关资源
      最近更新 更多