Search code examples
cstrcmpgetopt

Optarg string compare C


I am a newbie in C programming, I have some experiences about C++, but nothing with C. I have a question about getopt optarg argument, which is string. I want to check if input argument of -x flag is equal to "dog". My current code looks like:

int main(int argc, char** argv){
  int c;
  extern char *optarg;
  extern int optind;
  extern int optopt;
  int sum=0;
  while ( (c = getopt(argc, argv, ":x:h")) != -1) {
    switch (c) {
        case 'h': getHelp();
                   break;
        case 'x': if(strcmp("dog", optarg)== 0){
                        sum = 1;
                    } else {
                        sum = 0;
                    }
                   break;
    }
}

Summarized, I want to check whether input variable for -x flag is dog or not (if so, the variable sum changes to 0). In my case the sum variable is always 0, even though input is ' ./main -x dog'. Thank you all in advance!


Solution

  • Comment was not allowing me to indent the output. So here it is an answer. I tried the code in the question and I see the correct output.

    [tmp]$./a.out -x cat
    Sum = 0
    [tmp]$./a.out -x dog
    Sum = 1
    

    Here is the code:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char** argv){
      int c;
      extern char *optarg;
      extern int optind;
      extern int optopt;
      int sum=0;
      while ( (c = getopt(argc, argv, ":x:h")) != -1) {
          switch (c) {
              case 'h':
                    break;
              case 'x':
                    if(strcmp("dog", optarg)== 0){
                        sum = 1;
                    } else {
                        sum = 0;
                    }
                    break;
            }
        }
    
        printf("Sum = %d\n", sum);
    }