- #include <iostream>
- #include <boost/program_options.hpp>
- namespace po = boost::program_options;
- int main(int argc, char *argv[])
- {
- po::variables_map vm;
- po::options_description gen("general options");
- gen.add_options()
- ("int", po::value<int>(), "int test")
- ("help,h", "Display this message.")
- ("string", po::value<std::string>(), "string test")
- ("vector", po::value<std::vector<std::string>>(), "vector test")
- ("param", po::value<std::vector<std::string>>(), "param test");
- //位置参数项, 添加此项后可以不写 --param
- po::positional_options_description p;
- p.add("param", -1);
- try
- {
- po::store(po::command_line_parser(argc, argv)
- .options(gen) // Parse options.
- .positional(p) // Remainder as --param.
- .run(),
- vm);
- po::notify(vm); // Invoke option notify functions.
- }
- catch (std::exception const&)
- {
- std::cerr << "Incorrect command line syntax." << std::endl;
- std::cerr << "Use '--help' for a list of options." << std::endl;
- return 1;
- }
- if (vm.count("string"))
- std::cout << vm["string"].as<std::string>() << std::endl;
- if (vm.count("int"))
- std::cout << vm["int"].as<int>() << std::endl;
- if (vm.count("vector"))
- {
- auto &vs = vm["vector"].as<std::vector<std::string>>();
- for(auto &v : vs)
- {
- std::cout << v << " ";
- }
- std::cout << std::endl;
- }
- if (vm.count("help"))
- {
- std::cerr << gen << std::endl;
- }
- if (!vm.count("param"))
- {
- std::cout << "no --param"<<std::endl;
- }
- else
- {
- std::cout << "param : ";
- auto &vs1 = vm["param"].as<std::vector<std::string>>();
- for (auto &v : vs1)
- {
- std::cout << v << " ";
- }
- std::cout << std::endl;
- }
- return 0;
- }