2014-03-12 99 views
0

因此,我正在完成一個項目,只剩下一件事情要做,正確處理命令行參數。我以爲我讓他們處理,但顯然我錯了...可以有兩組不同的命令行參數可以進來,這裏是我所說的例子:./hw34 -c 385 280 50 balloons.ascii.pgm balloonCircle.pgm./hw34 -e 100 balloons.ascii.pgm balloonEdge.pgm處理特定的命令行參數

這是我曾試圖處理這些參數,但是這似乎並沒有工作: if(argc==5) && isdigit(atoi(argv[2]))){else if(argc==7 && isdigit(atoi(argv[2])) && isdigit(atoi(argv[3])) && isdigit(atoi(argv[4]))){

什麼我卡在試圖找出如果的argv [X]是數字或沒有。

回答

3

你應該嘗試以不同的方式處理命令行。

喜歡的東西:

./hw34 -c 「385,280,50」 balloons.ascii.pgm balloonCircle.pgm

./hw34 -e 100 balloons.ascii.pgm balloonEdge.pgm

然後結合getopt進行命令行處理,並將strtok與參數列表的拆分組合在一起,您應該可以實現您想要的功能。

主要優點是您不必擔心命令行中參數的數量或位置。

+0

謝謝,我會試試這個 – kevorski

1

典型main function帶參數的原型是

int main(int argc, char* argv[]); 

argc哪裏是參數char* argv[]的數量, - 這些參數的字符串數組。數組的第一個元素 - argv[0] - 是程序的名稱。

要檢查參數是一個數字就可以使用它返回轉換的狀態與strtol功能:

char* tail; 
long n = strtol(argv[2], &tail, 10); // 10 is the base of the conversion 

然後一個號碼後檢查它指向該字符串的部分的尾部(如果有的話) :

if (tail == argv[2]) { // not a number 
    // ... 
} else if (*tail != 0) { // starts with a number but has additional chars 
    // ... 
} else { // a number, OK 
    // ... 
} 
+0

我明白,但無論如何檢查,看看他們是否是數字。 – kevorski

1

argv的陣列。沒有整數。

您可以輕鬆地測試,如果轉化率可以通過使用strtol,然後檢查是否所有字符都消耗:

char const * str = "123"; 
char * endptr; 
long number = strtol(str, &endptr, 0); // do the conversion to long integer 
if(&str[strlen(str)] == endptr) // endptr should point at the end of original string 
    printf("ok"); 
else 
    printf("error");