2015-11-02 38 views
0

我需要將負數傳遞給getopt,並且我想知道是否有一種簡單的方法可以將getopt使用的前綴(即' - '字符在case語句中標記)更改爲不同的字符像' - '或'+'。將負數傳遞給Getopt

我是否需要使用Getopt :: Long來更改前綴?

回答

0

我不認爲有一種方法可以將命令行參數前綴更改爲除-(或--使用getopt_long())之外的任何內容。但是,如果您需要傳遞負數,則應該將參數定義爲「required_argument」。例如,下面是一個使用getopt_long_only方法獲取命令行參數的簡短getopt的方法:

// personaldetails.cpp 

// compile with: 
// g++ -std=c++11 personaldetails.cpp -o personaldetails 
#include <iostream> 
#include <string> 
#include <vector> 
#include <getopt.h> 

int main (int argc, char** argv) 
{ 
    // Define some variables 
    std::string name = "" ; 
    int age = 0 ; 
    double weight = 0.0 ; 

    // Setup the GetOpt long options. 
    std::vector<struct option> longopts ; 
    longopts.push_back({"Name", required_argument, 0, 'N'}) ; 
    longopts.push_back({"Age", required_argument, 0, 'A'}) ; // <- IMPORTANT 
    longopts.push_back({"Weight",required_argument, 0, 'W'}) ; // <- IMPORTANT 
    longopts.push_back({0,0,0,0}) ; 

    // Now parse the options 
    while (1) 
    { 
     int c(0) ; 
     int option_index = -1; 

     c = getopt_long_only (argc, argv, "A:N:W:", 
           &longopts[0], &option_index); 

     /* Detect the end of the options. */ 
     if (c == -1) break; 

     // Now loop through all of the options to fill them based on their values 
     switch (c) 
     { 
      case 0: 
       /* If this option set a flag, do nothing else now. */ 
       break ; 
      case '?': 
       // getopt_long_omly already printed an error message. 
       // This will most typically happen when then an unrecognized 
       // option has been passed. 
       return 0 ; 
      case 'N': 
       name = std::string(optarg) ; 
       break ; 
      case 'A': 
       age = std::stoi(optarg) ; 
       break ; 
      case 'W': 
       weight = std::stod(optarg) ; 
       break ; 
      default: 
       // Here's where we handle the long form arguments 
       std::string opt_name(longopts[option_index].name) ; 
       if (opt_name.compare("Name")==0) { 
        name = std::string(optarg) ; 
       } else if (opt_name.compare("Age")==0) { 
        age = std::stoi(optarg) ; 
       } else if (opt_name.compare("Weight")==0) { 
        weight = std::stod(optarg) ; 
       } 
       break ; 
     } 
    } 

    // Print the persons details 
    std::cout << "Name : " << name << std::endl; 
    std::cout << "Age : " << age << std::endl; 
    std::cout << "Weight: " << weight << std::endl; 

    return 0 ; 
} 

這裏的關鍵部分是,在longopts我設置我要轉換成整數的參數和雙倍有required_argument。這告訴GetOpt到期望另一個參數,你已經在命令行上聲明它。這意味着GetOpt將在參數的命令行參數之後的參數中讀入該命令行參數。對於我們想要通過單個參數(即-N,-A-W)的情況,這裏通過"N:A:W:"來getopt很重要。 :對於單個字符參數基本上做同樣的事情,如required_argument對長格式所做的那樣。

運行腳本我可以這樣做:

$ ./personaldetails -Name Sally -Age -45 -Weight 34.5 
Name : Sally 
Age : -45 
Weight: 34.5 

$./personaldetails -N Sally -A -45 -W -34.5 
Name : Sally 
Age : -45 
Weight: -34.5 

注意,因爲腳本使用getopt_long_only()我可以傳遞參數參數的長形式單一-