#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::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;
}

 

运行:

boost::program_options 解析命令行参数

 

 注意:

  1. po::options_description desc("Allow options"); /*此行,用的是options_description类, 本人犯了错,记下来警醒自己*/
  2. po::parse_command_line(argc, argv, desc) /*这句代码, 当在命令行输入了参数,但不带其对应该的值,就会运行报错,所以需要try来捕捉异常*/

相关文章:

  • 2021-09-07
  • 2021-07-31
  • 2021-11-28
  • 2021-12-05
  • 2021-12-09
  • 2022-01-20
  • 2021-09-29
  • 2021-10-20
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2022-02-02
相关资源
相似解决方案