繁体   English   中英

使用boost.program_options处理' - '

[英]Handling '-' with 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 - - -时引发异常cat - - -

无法识别的选项' - '

我希望它看到-作为位置参数,我需要在完整文件列表中以正确的顺序。 我怎么能实现这个目标?

UPDATE

我有一半修复。 我需要

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);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM