No arguments default behavior with Boost.Program_options?
Asked Answered
M

2

6

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.

Mitchel answered 14/5, 2013 at 21:10 Comment(0)
A
7

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

Adaminah answered 14/5, 2013 at 21:16 Comment(0)
M
14

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.

Minstrel answered 24/5, 2013 at 3:48 Comment(0)
A
7

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

Adaminah answered 14/5, 2013 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.