源码:
#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 << "输入的参数中存在未定义的选项!
";
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来捕捉异常*/