gpt4 book ai didi

c++ - 命令行解析器忽略必需的选项

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:09 24 4
gpt4 key购买 nike

给定以下程序

#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

最佳答案

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

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

关于c++ - 命令行解析器忽略必需的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com