Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost program options multiple values for an option

When I type a.out -i file0 file1 at the command line, I want the option -i to receive both file0 and file1 But, -i only receive file0 but not file1

But, I found that I had to type a.out -i file0 -i file1 to make -i option to receive both file0 and file1

Can boost::program_options do this?

Code adapted from http://www.boost.org/doc/libs/1_62_0/libs/program_options/example/options_description.cpp

#include <boost/program_options.hpp>

using namespace boost;
namespace po = boost::program_options;

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

// A helper function to simplify the main part.
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
    return os;
}

int main(int ac, char* av[])
{
    try {
        int opt;
        int portnum;
        po::options_description desc("Allowed options");
        desc.add_options()
                ("help", "produce help message")
                ("input-file,i", po::value< vector<std::string> >(), "input "
                        "file")
                ;

        po::variables_map vm;
        po::store(po::command_line_parser(ac, av).
                options(desc).run(), vm);
        po::notify(vm);

        if (vm.count("help")) {
            cout << "Usage: options_description [options]\n";
            cout << desc;
            return 0;
        }


        if (vm.count("input-file"))
        {
            cout << "Input files are: "
                 << vm["input-file"].as< vector<std::string> >() << "\n";
        }

    }
    catch(std::exception& e)
    {
        cout << e.what() << "\n";
        return 1;
    }
    return 0;
}
like image 875
hamster on wheels Avatar asked Feb 24 '17 00:02

hamster on wheels


Video Answer


1 Answers

From Sean Cline:

Flagging your value as multitoken should make it behave as you expect.

("input-file,i", po::value<vector<std::string>>()->multitoken(), "input file")
like image 109
Peeaytchpee Avatar answered Sep 23 '22 03:09

Peeaytchpee