2009-04-29 85 views
1

我:幫助比較的argv的字符串

int main(int argc, char **argv) { 
    if (argc != 2) { 
     printf("Mode of Use: ./copy ex1\n"); 
     return -1; 
    } 

    formatDisk(argv); 
} 

void formatDisk(char **argv) { 
    if (argv[1].equals("ex1")) { 
     printf("I will format now \n"); 
    } 
} 

我如何檢查是否argv等於"ex1"用C? 這是否已經有一個功能? 謝謝

回答

16
#include <string.h> 
if(!strcmp(argv[1], "ex1")) { 
    ... 
} 
+1

您是否還應該檢查null或確保首先存在此索引? – 2009-04-29 19:06:35

+2

argc給出argv中的參數個數,所以檢查(如果argc!= 2)可以確保argv [1]存在。 – 2009-04-29 19:08:40

1

只是給和使用字符串和動態分配新字符串的示例。也許有用,當你不知道的argv的大小[?]

// Make the string with the value you want compared 
char testString[] = "-command"; 

// Make a char pointer, use new to allocate the memory 
// the size is determined by string length of argv[1] 
char * strToTest = new char[ strlen(argv[1]) ]; 

// Now we can copy the contents of argv[1] into strToTest as they are equal size 
strcpy(strToTest, argv[1]); 

// Now strcmp returns True if the two strings match 
if (strcmp(testString, strToTest) { 
//do somthing here ... 
} 

注意,如果你以後要使用strToTest別的東西,你應該使用「刪除」 以確保內存空間是未-allocated。這是避免內存泄漏的良好做法。