2017-07-27 70 views
1
static struct option long_options[] = 
{ 
    {"r", required_argument, 0, 'r'}, 
    {"help",  no_argument,  0, 'h'}, 
    {0, 0, 0, 0} 
}; 


int option_index = 0; 
char c; 
while((c = getopt_long(argc, argv, "r:h", long_options, &option_index)) != -1) 
{ 
    switch(c) 
    { 
     case 'r': 
      break; 
     case 'h': 
      return EXIT_SUCCESS; 
    } 
} 

如何使h成爲默認參數,因此如果此程序在沒有任何參數的情況下運行,那麼它將如同使用-h運行一樣?在C++中使用getopt時打印默認參數

回答

1

也許嘗試這樣的事:

static struct option long_options[] = 
{ 
    {"r", required_argument, 0, 'r'}, 
    {"help", no_argument,  0, 'h'}, 
    {0, 0, 0, 0} 
}; 

int option_index = 0; 
char c = getopt_long(argc, argv, "r:h", long_options, &option_index); 
if (c == -1) 
{ 
    // display help... 
    return EXIT_SUCCESS; 
} 

do 
{ 
    switch(c) 
    { 
     case 'r': 
      break; 

     case 'h': 
     { 
      // display help... 
      return EXIT_SUCCESS; 
     } 
    } 

    c = getopt_long(argc, argv, "r:h", long_options, &option_index); 
} 
while (c != -1); 

或者這樣:

static struct option long_options[] = 
{ 
    {"r", required_argument, 0, 'r'}, 
    {"help", no_argument,  0, 'h'}, 
    {0, 0, 0, 0} 
}; 

int option_index = 0; 
char c = getopt_long(argc, argv, "r:h", long_options, &option_index); 
if (c == -1) 
    c = 'h'; 

do 
{ 
    switch(c) 
    { 
     case 'r': 
      break; 

     case 'h': 
     { 
      // display help... 
      return EXIT_SUCCESS; 
     } 
    } 

    c = getopt_long(argc, argv, "r:h", long_options, &option_index); 
} 
while (c != -1); 
0

爲什麼不創建一個printUsage功能,這樣做。

if (c == 0) { 
    printUsage(); 
    exit(-1); 
}