Help comparing an argv string

21,555

Solution 1

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

Solution 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 ...
}
Share:
21,555
UcanDoIt
Author by

UcanDoIt

Updated on July 23, 2022

Comments

  • UcanDoIt
    UcanDoIt almost 2 years

    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

  • Chris Ballance
    Chris Ballance about 15 years
    Should you also be checking for null or ensure that this index exists first?
  • plankalkul
    plankalkul about 15 years
    argc gives the count of arguments in argv, so the check of (if argc != 2) assures that argv[1] exists.
  • poundifdef
    poundifdef about 15 years
    Also worth noting the strncmp() function, which compares the first 'n' bytes of the strings. (manpagez.com/man/3/strncmp)
  • Raja
    Raja over 10 years
    why do we need a copy of argv[1]? strcmp takes const char *
  • Zv_oDD
    Zv_oDD about 3 years
    @Raja; The copy isn't necessary. It purely for the sake of cramming extra string function examples in to the answer. Because if you're looking this question up, you probably want to see those too : ) ... as stated in the first two sentences of the answer.
  • Admin
    Admin about 3 years
    new is not very c-ish :> (answering a post 12 years old)