boost program options multiple values for an option
Asked Answered
S

1

18

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;
}
Sauncho answered 24/2, 2017 at 0:22 Comment(2)
Flagging your value as multitoken should make it behave as you expect. ("input-file,i", po::value<vector<std::string>>()->multitoken(), "input file")Subir
@SeanCline Consider making this an answer instead of a comment.Numismatist
M
22

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")
Malocclusion answered 28/2, 2018 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.