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

293 阅读1分钟
  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. }