加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 解析位置参数

发布时间:2020-12-16 05:27:20 所属栏目:百科 来源:网络整理
导读:考虑从boost程序选项 examples中采用的以下琐碎程序 #include boost/program_options.hpp#include boost/version.hpp#include iostreamintmain( int argc,char** argv ){ namespace po = boost::program_options; po::options_description desc("Options");
考虑从boost程序选项 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;
    }
}

以下行为如预期:

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

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$

但是,当引入一个位置论证时,我感到非常惊讶,没有被标记为错误

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

为什么boost :: program_options :: too_many_positional_options_error异常不会抛出?

解决方法

当我明确指出不支持位置选项:
const po::positional_options_description p; // note empty positional options
    po::store(
            po::command_line_parser( argc,argv).
                      options( desc ).
                      positional( p ).
                      run(),vm
                      );

我得到预期的行为:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读