boost::program_options 解析命令行参数
源码:
#include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char** argv) { int compression = -1; po::options_description desc("Allow options"); desc.add_options() ("help", "produce help message") ("compression", po::value<int>(), "set compression level"); //("help,h", "produce help message") //("compression", po::value<int>(&compression)->default_value(10), "set compression level"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); // po::store(po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(), vm); po::notify(vm); } catch (...) { std::cout << "unkown args" << std::endl; return 0; } if (vm.count("help")) { cout << desc << endl; return 1; } if (vm.count("compression")) { cout << "Compression level was set to " << compression << endl; } else { cout << "Compression level was not set." << endl; } return 0; }
运行:
注意:
- po::options_description desc("Allow options"); /*此行,用的是options_description类, 本人犯了错,记下来警醒自己*/
- po::parse_command_line(argc, argv, desc) /*这句代码, 当在命令行输入了参数,但不带其对应该的值,就会运行报错,所以需要try来捕捉异常*/