码迷,mamicode.com
首页 > 其他好文 > 详细

program_options禁止命令行短参数

时间:2015-05-31 16:37:02      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

典型的 boost program_options的用法如下:

#include <boost/program_options.hpp>

using namespace boost::program_options;
using namespace std;

int main(int argc, char* argv[]) // 需要命令行参数
{
   int intValue;
   options_description opts("Mysql performance options");  //增加两个程序选项
   opts.add_options()
      ("help,h", "help message")
      ("int", value<string>(&intValue)->default_value(1), "a int value")
   
   variables_map vm;  // 选项存储map容器
   store(parse_command_line(argc, argv, opts), vm); //解析参数并存储到vm中    notify(vm);

   cout << filename << endl;
}

假设编译出的二进制文件为 test,运行 ./test --int 5。如果这时候想传入参数-5,写法应该是 ./test --int -5。由于-5与短参数格式难以分辨(-5也是短参数的格式),这时候程序依旧能够编译通过,但是运行的时候会出现参数使用错误。为了支持值为负数的参数,我们可以禁用短参数。具体做饭为将store()函数的调用改为

store(parse_command_line(argc, argv, opts,
po::command_line_style::unix_style ^ po::command_line_style::allow_short),
vm);

program_options的默认风格为unix_style, 通过 program_options官方文档 可以看到 unix_style是几种 style与的结果,我们只要使用异或的方式就可以把其中某种style去掉。

enum style_t 
{
    allow_long =  1,
    allow_short =  allow_long << 1, 
    allow_dash_for_short =  allow_short << 1, 
    allow_slash_for_short =  allow_dash_for_short << 1, 
    long_allow_adjacent =  allow_slash_for_short << 1, 
    long_allow_next =  long_allow_adjacent << 1, 
    short_allow_adjacent =  long_allow_next << 1, 
    short_allow_next =  short_allow_adjacent << 1, 
    allow_sticky =  short_allow_next << 1, 
    allow_guessing =  allow_sticky << 1, 
    case_insensitive =  allow_guessing << 1, 
    allow_long_disguise =  case_insensitive << 1, 
    unix_style =  (allow_short | short_allow_adjacent
                          | short_allow_next | allow_long
                          | long_allow_adjacent | long_allow_next
                          | allow_sticky | allow_guessing 
                          | allow_dash_for_short), 
     default_style =  unix_style };

现在重新编译运行程序,运行 ./test --int -5 就可以正确输出 -5了。

program_options禁止命令行短参数

标签:

原文地址:http://www.cnblogs.com/CasperWu/p/4542080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!