Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost program_options accept all values after last flag

Is there a way to collect all of the values after a specified argument with boost::program_options? There are two caveats that I need to take care of though, I need to accept unrecognized arguments, and I need to accept values that could contain dashes. I've tried playing around with command_line_parser vs parse_command_line and I can get either unrecognized or values that contain dashes, but not both.

Example: ./myprog Ignore1 Ignore2 --Accept 1 --AlsoAccept 2 --AcceptAll 1 2 -3 4

I'm not really concerned with verifying that --AcceptAll is the last flag passed; I'm just looking for logic that returns a vector of strings for everything after that flag.

like image 362
sfpiano Avatar asked Oct 14 '22 02:10

sfpiano


2 Answers

have you tried positional options?

#include <boost/program_options.hpp>

#include <boost/foreach.hpp>

#include <iostream>
#include <string>

namespace po = boost::program_options;

int
main( unsigned int argc, char** argv )
{
    std::string foo;
    std::vector<std::string> extra;
    po::options_description desc;
    desc.add_options()
        ("foo", po::value<std::string>(&foo), "some string")
        ("extra-options", po::value(&extra), "extra args" )
        ;

    po::positional_options_description p;
    p.add("extra-options", -1);

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

    BOOST_FOREACH( const std::string& i, extra ) {
        std::cout << i << std::endl;
    }

    return 0;
}

sample session

samm@macmini ~> ./a.out --foo bar far hello world how are you
far
hello
world
how
are
you
samm@macmini ~>
like image 69
Sam Miller Avatar answered Oct 20 '22 15:10

Sam Miller


The answer to your question is virtually the same as the answer to my question about handling the end-of-options option -- properly: Using '--' as end-of-options marker with boost::program_options. The only thing you need to change is to substitute --AcceptAll for -- in the extra_style_parser.

like image 44
uckelman Avatar answered Oct 20 '22 15:10

uckelman