开发者

Parsing positional arguments

开发者 https://www.devze.com 2023-01-18 13:10 出处:网络
Consider the following trivial program adopted from the boost program options examples #include <boost/program_options.hpp>

Consider the following trivial program adopted from the boost program options examples

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

#include <iostream>

int
main( int argc, char** argv )
{
    namespace po = boost::program_options;

    po::options_description desc("Options");

    unsigned foo;
    desc.add_options()
        ("help,h", "produce help message")
        ("foo", po::value(&foo), "set foo") 
        ;

    po::variables_map vm;
    try {
        po::store(
                po::parse_command_line( argc, argv, desc ),
                vm
                );
        po::notify( vm );

        if ( vm.count("help") ) {
            std::cout << desc << "\n";
            std::cout << "boost version: " << BOOST_LIB_VERSION << std::endl;
        }
    } catch ( const boost::program_options::error& e ) {
        std::cerr << e.what() << std::endl;
    }
}

the following behavior is as expected:

samm$ ./a.out -h
Options:
  -h [ --help ]         produce help message
  --foo arg             set foo开发者_如何学C

boost version: 1_44
samm$ ./a.out --help
Options:
  -h [ --help ]         produce help message
  --foo arg             set foo

boost version: 1_44
samm$ ./a.out --foo 1
samm$ ./a.out --asdf
unknown option asdf
samm$

However, I was surprised when introducing a positional argument, it was not flagged as an error

samm$ ./a.out foo bar baz
samm$

Why is boost::program_options::too_many_positional_options_error exception not thrown?


when I explicitly indicate no positional options are supported:

    const po::positional_options_description p; // note empty positional options
    po::store(
            po::command_line_parser( argc, argv).
                      options( desc ).
                      positional( p ).
                      run(),
                      vm
                      );

I get the expected behavior:

samm$ ./a.out asdf foo bar
too many positional options
samm$
0

精彩评论

暂无评论...
验证码 换一张
取 消