Su JK
Su JK

Reputation: 171

Boost::Positional Options unable to make all arguments positional

Following is the code where boost::program_options have been used.

#include <iostream>
#include <vector>

#include <boost/program_options.hpp>

int main (int argc, char* argv[]) {
    int n;
    std::string mps_name;

    boost::program_options::options_description desc("options");
    desc.add_options()
        ("file", boost::program_options::value<std::string>(&mps_name)->required(),
         "input file")
        (",n", boost::program_options::value<int>(&n)->required(),
         "number")
        ("help", "this help message")
        ;

    boost::program_options::positional_options_description p;
    p.add("file", 1);
    p.add(",n", 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 << e.what() << std::endl;
        return -1;
    }

    std::cout << "command line arguments parsed" << std::endl;

    return 0;
} // main

When the code is executed with all arguments as positional arguments. boost throws the exception unrecognised option '5'. When the code was executed with ./a.out earth 5

Code works perfect when executed with the command ./a.out --file earth -n 5

Upvotes: 1

Views: 1164

Answers (1)

sehe
sehe

Reputation: 393114

The problem is that positionals correspond to option descriptions by long name only. Here's a working version:

boost::program_options::options_description desc("options");
desc.add_options()
    ("file", boost::program_options::value<std::string>(&mps_name)->required(), "input file")
    ("n,n", boost::program_options::value<int>(&n)->required(), "number")
    ("help", "this help message")
    ;

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

Live On Coliru

Prints

./a.out ltuae 42
command line arguments parsed: ltuae 42

Upvotes: 1

Related Questions