mercredi 6 septembre 2017

boost program options: argument being detected more than once

Following code detects the arguments being specified more than once.

The command line arguments parser is implemented to ensure that the user provides a string (mps-file), integer (n) and a sequence of integer (0, n-1) allowing others to be optional.

However, when the code is compiled using the following flags: g++ -std=c++11 test.cpp /home/not_me/my_lib/boost_1_64_0/stage/lib/libboost_program_options.s

Which compiles perfectly. But when executed in the following way it throws the following exception.

/src/a.out --mps-file earth.mps --n 5 --size 10 --seed 10 --order 0 1 2 3 4
error: option '--mps-file' cannot be specified more than once

But if executed using the following command it runs fine:
./src/a.out earth.mps 5 10 10 --order 0 1 2 3 4

Full code:

#include <iostream>
#include <numeric>

#include <boost/program_options.hpp>

int main (int argc, char* argv[]) {

    int n;
    int sample_size = 10;
    std::random_device rd;
    int seed = rd();
    std::string mps_name;
    std::vector<int> order;

    boost::program_options::options_description desc("options");
    desc.add_options()
        ("mps-file", boost::program_options::value<std::string>(&mps_name)->required(), "input mps file")
        ("n", boost::program_options::value<int>(&n)->required(), "number of variables")
        ("size", boost::program_options::value<int>(&sample_size)->default_value(sample_size), "size of sample")
        ("seed", boost::program_options::value<int>(&seed)->default_value(seed), "seed value")
        ("order", boost::program_options::value<std::vector<int>>(&order)->required(), "ordering")
        ("help", "this help message")
        ;

    boost::program_options::positional_options_description p;
    p.add("mps-file", 1);
    p.add("n", 1);
    p.add("order", -1);

    boost::program_options::variables_map vm;

    try {
        boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
                                      options(desc).positional(p).run(), vm);

        if (vm.count("help") || argc == 1) {
            std::cout << "usage: " << argv[0] << " [options]" << std::endl;
            std::cout << desc;
            return -1;
        }

        boost::program_options::notify(vm);
    }
    catch (std::exception& e) {
        std::cout << "error: " << e.what() << std::endl;
        return -1;
    }

    std::vector<int> temp = order;
    std::sort(temp.begin(), temp.end());
    for (int i = 0; i < n; ++i) {
        if (temp[i] == i) { continue; }
        std::cout << "incorrect ordering given" << std::endl;
        return -1;
    }

    if (n != order.size()) {
        std::cout << "mismatch between the 'n' and given ordering" << std::endl;
        return -1;
    }

    return 0;
} // main

Aucun commentaire:

Enregistrer un commentaire