Search code examples
c++boostboost-program-options

boost::program_options read an integer array from console


I want to read an integer array from console using boost::program_options. The length of the array is not known and I don't want to read all the data in one attempt. How can I do that?

What I am doing now is

$ ./foo --array "1, 2, 3"

and then populate arr[] by splitting input string.

But I want something like

$ ./foo --array 1 --array 2 --array 3

and read it in arr[]. Also want to know the length of arr[], don't want to make that a command-line param.


Solution

  • Use a vector instead of an array. Then, simply specify a vector as the option type:

    po::options_description desc("Allowed options");
    desc.add_options()
        ("array", po::value< vector<int> >())
    ;
    

    Each option on the command line will be appended to the vector.