boost 分析命令行参数

时间:2021-09-14 20:59:32
  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. variables_map vm;
  17. try
  18. {
  19. store(parse_command_line(argc,argv,opts),vm); // 分析参数
  20. }
  21. catch(boost::program_options::error_with_no_option_name &ex)
  22. {
  23. cout<<ex.what()<<endl;
  24. }
  25. notify(vm); // 将解析的结果存储到外部变量
  26. if (vm.count("help"))
  27. {
  28. cout<<opts<<endl;
  29. return -1;
  30. }
  31. if(vm.count("test1"))
  32. {
  33. cout<<vm["test1"].as<string>()<<endl;
  34. }
  35. cout<<one<<endl;
  36. cout<<mult.size()<<endl;
  37. getchar();
  38. return 0;
  39. }

[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