Help comparing an argv string

China☆狼群 提交于 2019-12-10 23:40:35

问题


I have:

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");
   }
}

How can I check if argv is equal to "ex1" in C? Is there already a function for that? Thanks


回答1:


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



回答2:


Just to give and example of using strings and dynamically allocating new strings. Probably useful when you don't know the size of 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 ...
}

Note that if you want to use strToTest for something else later, you should use "delete" to make sure the memory space is un-allocated. This is good practice to avoid memory leaks.



来源:https://stackoverflow.com/questions/803776/help-comparing-an-argv-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!