帮助比较argv字符串

时间:2009-04-29 19:03:00

标签: c 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"? 是否已有功能? 感谢

2 个答案:

答案 0 :(得分:18)

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

答案 1 :(得分: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,则应使用“删除” 确保内存空间未分配。这是避免内存泄漏的好方法。