Question

I am using Boost::Program_options to parse my command line and adapted some code from the tutorial as following:

try {
    po::options_description desc("Allowed options");

    desc.add_options()
        ("help,h", "output help message")
        ("width,w", po::value<int>()->required(), " width")
    ;

    po::positional_options_description p;
    p.add("width", 1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).
              options(desc).positional(p).run(), vm);

    if (vm.count("help")) {
        std::cout << "USAGE: " << av[0] << &p <<  std::endl;
        return 0;
    }

    po::notify(vm);

    if (vm.count("width")) {
        std::cout << "width: " << vm["width"].as<int>() << "\n";
    }
} catch (std::exception& e) {
    std::cout << e.what() << std::endl;
    return 1;
} catch (...) {
    std::cout << "Exception of unknown type!" << std::endl;
}

I'd like to show help when no arguments are passed but I didn't found a way to get the total number of arguments variables_map without relying on argc.

Était-ce utile?

La solution 2

argc is the way to go here, program_options does not expose how many options were set. Don't overengineer.

Autres conseils

I've used

if ( vm.count("help") || argc == 1) {

since argc always at least contains the name of the program, running it with no arguments will display help.

doh... nevermind. not sure how I missed the fact that you specifically didn't want this solution.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top