Don't know how to check input arguments in C

Viewed 258

I'd like to check that the second input argument to my C program is either -f or -p. I'm using if statements to check this, and for some reason it doesn't recognize the argument as the string, yet when I print the argument it looks identical. I've tried it two ways, the first by copying the argument to a character array, and the second by checking the argument directly. What am I missing?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char flag[3] = "";
    memcpy(flag, argv[1],3);
    printf("%s\n", flag);

    // check that the second argument is either -f or -p
    if (flag == "-f")
    {
        printf("1");
    }
    else if (argv[1] == "-p")
    {
        printf("2");
    }
    else
    {
        fprintf(stderr, "ERROR: Second argument %s must be <-f> or <-p>\n", argv[1]);
        exit(EXIT_FAILURE);
    }
}
    
1 Answers

C is not C++ or Python. The == operator does not work for comparing strings. What is does, is not what you intend it to do. It compares two pointers instead.

You shall use strcmp family of functions for that.

if(strcmp(flag, "-f") == 0){
 /* equals */
}
if(strncmp(flag, "-f", 2) == 0){
 /* equals */
}
Related