Boost :: Positional选项无法使所有参数都位于位置

时间:2017-08-22 18:54:56

标签: c++ boost boost-program-options

以下是使用boost::program_options的代码。

#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

当代码以所有参数作为位置参数执行时。 boost抛出异常unrecognised option '5'。使用./a.out earth 5

执行代码时

使用命令./a.out --file earth -n 5

执行代码时,代码工作正常

1 个答案:

答案 0 :(得分:0)

问题是,位置对应于仅通过长名称的选项描述。这是一个有效的版本:

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

打印

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