程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> program_options禁止命令行短參數,programoptions

program_options禁止命令行短參數,programoptions

編輯:C++入門知識

program_options禁止命令行短參數,programoptions


典型的 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了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved