boost::program_options 解析命令行參數
阿新 • • 發佈:2019-03-20
val comm amp value 命令行 圖片 was oos lse
源碼:
#include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char** argv) { int compression; 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::notify(vm); } catch (...) { std::cout << "輸入的參數中存在未定義的選項!\n"; 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來捕捉異常*/
boost::program_options 解析命令行參數