帮助比较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"); } } 

如何在C中检查argv是否等于"ex1" ? 是否已有function? 谢谢

 #include  if(!strcmp(argv[1], "ex1")) { ... } 

只是给出使用字符串和动态分配新字符串的例子。 当你不知道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,则应使用“delete”来确保未分配内存空间。 这是避免内存泄漏的好方法。