1
以下是已使用boost::program_options
的代碼。Boost ::位置選項無法使所有參數位置
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
int main (int argc, char* argv[]) {
int n;
std::string mps_name;
boost::program_options::options_description desc("options");
desc.add_options()
("file", boost::program_options::value<std::string>(&mps_name)->required(),
"input file")
(",n", boost::program_options::value<int>(&n)->required(),
"number")
("help", "this help message")
;
boost::program_options::positional_options_description p;
p.add("file", 1);
p.add(",n", 1);
boost::program_options::variables_map vm;
try {
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
if (vm.count("help") || argc == 1) {
std::cout << "usage: " << argv[0] << " [options]" << std::endl;
std::cout << desc;
return -1;
}
boost::program_options::notify(vm);
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
return -1;
}
std::cout << "command line arguments parsed" << std::endl;
return 0;
} // main
當代碼以所有參數作爲位置參數執行時。 boost
拋出異常unrecognised option '5'
。當代碼與./a.out earth 5
代碼執行時與命令./a.out --file earth -n 5