使用boost.program_options处理' - '

时间:2013-04-01 19:33:17

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

在你说OVERKILL之前,我不在乎。

如何让Boost.program_options处理所需的cat选项-

我有

// visible
po::options_description options("Options");
options.add_options()("-u", po::value<bool>(), "Write bytes from the input file to the standard output without delay as each is read.");

po::positional_options_description file_options;
file_options.add("file", -1);

po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options).positional(file_options).run(), vm);
po::notify(vm);

bool immediate = false;
if(vm.count("-u"))
  immediate = true;
if(vm.count("file"))
  support::print(vm["file"].as<vector<string>>());

在我运行cat - - -时抛出异常:

  

无法识别的选项' - '

我希望它将-视为位置参数,我需要在完整文件列表中以正确的顺序使用它。我怎么能做到这一点?

更新

我有一半修复。我需要

po::options_description options("Options");
options.add_options()("-u", po::value<bool>(), "Write bytes from the input file to the standard output without delay as each is read.")
                    ("file", po::value< vector<string> >(), "input file");

po::positional_options_description file_options;
file_options.add("file", -1);

问题是,当输出参数时,我似乎只得到三个-中的两个:

if(vm.count("file"))
  support::print(vm["file"].as<vector<string>>());

support :: print很好地处理向量和东西。

1 个答案:

答案 0 :(得分:4)

您需要定义位置的命名程序选项,在您的情况下是file

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <string>
#include <vector>

namespace po = boost::program_options;

int
main( int argc, char* argv[] )
{
    std::vector<std::string> input;
    po::options_description options("Options");
    options.add_options()
        ("-u", po::value<bool>(), "Write bytes from the input file to the standard output without delay as each is read.")
        ("file", po::value(&input), "input")
        ;

    po::positional_options_description file_options;
    file_options.add("file", -1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(options).positional(file_options).run(), vm);
    po::notify(vm);

    bool immediate = false;
    if(vm.count("-u"))
        immediate = true;
    BOOST_FOREACH( const auto& i, input ) {
        std::cout << "file: " << i << std::endl;
    }
}

如果您不想点击

,这是一个coliru demo和输出
$ g++ -std=c++11 -O2 -pthread main.cpp -lboost_program_options && ./a.out - - -
file: -
file: -
file: -

如果你只看到3个位置参数中的2个,那很可能是因为argv[0]按照惯例是程序名,因此不被认为是参数解析。这可以在basic_command_line_parser模板

的源代码中看到
 37     template<class charT>
 38     basic_command_line_parser<charT>::
 39     basic_command_line_parser(int argc, const charT* const argv[])
 40     : detail::cmdline(
 41         // Explicit template arguments are required by gcc 3.3.1 
 42         // (at least mingw version), and do no harm on other compilers.
 43         to_internal(detail::make_vector<charT, const charT* const*>(argv+1, argv+argc+!argc)))
 44     {}