我讀過a getopt() example但它並沒有說明如何接受整數作爲參數的選項,比如cvalue
將是從示例代碼:如何將整數作爲命令行參數?
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort();
}
printf ("aflag = %d, bflag = %d, cvalue = %s\n",
aflag, bflag, cvalue);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
如果我跑了上面testop -c foo
,cvalue
會foo
,但如果我想要testop -c 42
?由於cvalue
是char *
類型,我可以將optarg
轉換爲(int)
嗎?我試過這樣做,而不使用getopt()
並直接訪問argv[whatever]
,並將其轉換爲整數,但在使用%d
進行打印時,我總是會得到一個很大的負數。我假設我沒有正確地提取argv[]
或某物,不確定...