使用boost.program_options处理'-'

Handling '-' with boost.program_options

本文关键字:处理 options boost program 使用      更新时间:2023-10-16

在你说" 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很好地处理了向量和其他东西

您需要定义命名程序选项,它是位置的,在您的例子中是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演示和输出,如果你不想点击

$ 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     {}