boost 分析命令行参数

[cpp] view plaincopy
 
  1. #include <boost/program_options.hpp>  
  2. #include <iostream>  
  3. #include <vector>  
  4. using namespace std;  
  5. using namespace  boost::program_options;  
  6. int main(int argc, char* argv[])  
  7. {  
  8.   string one ; // 外部变量 存储 参数one的值  
  9.   vector<string> mult;  
  10.   boost::program_options::options_description opts("test options");  
  11.   opts.add_options()  
  12.     ("help,h","help info")  
  13.     ("test1,t",value<string>(),"test aaa ")  
  14.     ("one,o",value<string>(&one)->default_value("one"),"test one default") // 默认值   
  15.     ("mult,m",value<vector<string> >(&mult)->multitoken(),"mult test"); //多个参数  
  16.   
  17.   variables_map vm;  
  18.   try  
  19.   {  
  20.     store(parse_command_line(argc,argv,opts),vm); // 分析参数  
  21.   }  
  22.   catch(boost::program_options::error_with_no_option_name &ex)  
  23.   {  
  24.     cout<<ex.what()<<endl;  
  25.   }  
  26.   
  27.   notify(vm); // 将解析的结果存储到外部变量  
  28.   if (vm.count("help"))  
  29.   {  
  30.     cout<<opts<<endl;  
  31.     return -1;  
  32.   }  
  33.   if(vm.count("test1"))  
  34.   {  
  35.    cout<<vm["test1"].as<string>()<<endl;  
  36.   }  
  37.     
  38.   cout<<one<<endl;  
  39.   cout<<mult.size()<<endl;  
  40.     
  41.   getchar();  
  42.   
  43.   return 0;  
  44. }  

[root@localhost test4]# g++ main.cpp  -l boost_program_options
[root@localhost test4]# ./a.out  -h
test options:
  -h [ --help ]           help info
  -t [ --test1 ] arg      test aaa 
  -o [ --one ] arg (=one) test one default
  -m [ --mult ] arg       mult test


[root@localhost test4]# ./a.out  -m f2 f3 f4 --test1 testbbbb
testbbbb
one
3

原文地址:https://www.cnblogs.com/lidabo/p/3953791.html