C++用BOOST解析命令行参数

  1. #include <iostream>
  2. #include <boost/program_options.hpp>
  3.  
  4. namespace po = boost::program_options;
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8. po::variables_map vm;
  9. po::options_description gen("general options");
  10. gen.add_options()
  11. ("int", po::value<int>(), "int test")
  12. ("help,h", "Display this message.")
  13. ("string", po::value<std::string>(), "string test")
  14. ("vector", po::value<std::vector<std::string>>(), "vector test")
  15. ("param", po::value<std::vector<std::string>>(), "param test");
  16.  
  17. //位置参数项, 添加此项后可以不写 --param
  18. po::positional_options_description p;
  19. p.add("param", -1);
  20. try
  21. {
  22. po::store(po::command_line_parser(argc, argv)
  23. .options(gen) // Parse options.
  24. .positional(p) // Remainder as --param.
  25. .run(),
  26. vm);
  27. po::notify(vm); // Invoke option notify functions.
  28. }
  29. catch (std::exception const&)
  30. {
  31. std::cerr << "Incorrect command line syntax." << std::endl;
  32. std::cerr << "Use '--help' for a list of options." << std::endl;
  33. return 1;
  34. }
  35.  
  36. if (vm.count("string"))
  37. std::cout << vm["string"].as<std::string>() << std::endl;
  38.  
  39. if (vm.count("int"))
  40. std::cout << vm["int"].as<int>() << std::endl;
  41.  
  42. if (vm.count("vector"))
  43. {
  44. auto &vs = vm["vector"].as<std::vector<std::string>>();
  45. for(auto &v : vs)
  46. {
  47. std::cout << v << " ";
  48. }
  49. std::cout << std::endl;
  50. }
  51.  
  52. if (vm.count("help"))
  53. {
  54. std::cerr << gen << std::endl;
  55. }
  56.  
  57. if (!vm.count("param"))
  58. {
  59. std::cout << "no --param"<<std::endl;
  60. }
  61. else
  62. {
  63. std::cout << "param : ";
  64. auto &vs1 = vm["param"].as<std::vector<std::string>>();
  65. for (auto &v : vs1)
  66. {
  67. std::cout << v << " ";
  68. }
  69. std::cout << std::endl;
  70. }
  71.  
  72. return 0;
  73. }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值