How to compare strings in an "if" statement? [duplicate]
Mia Lopez
I want to test and see if a variable of type "char" can compare with a regular string like "cheese" for a comparison like:
#include <stdio.h>
int main()
{ char favoriteDairyProduct[30]; scanf("%s",favoriteDairyProduct); if(favoriteDairyProduct == "cheese") { printf("You like cheese too!"); } else { printf("I like cheese more."); } return 0;
}(What I actually want to do is much longer than this but this is the main part I'm stuck on.) So how would one compare two strings in C?
15 Answers
You're looking for the function strcmp, or strncmp from string.h.
Since strings are just arrays, you need to compare each character, so this function will do that for you:
if (strcmp(favoriteDairyProduct, "cheese") == 0)
{ printf("You like cheese too!");
}
else
{ printf("I like cheese more.");
}Further reading: strcmp at cplusplus.com
if(strcmp(aString, bString) == 0){ //strings are the same
}godspeed
if(!strcmp(favoriteDairyProduct, "cheese"))
{ printf("You like cheese too!");
}
else
{ printf("I like cheese more.");
} 2 Have a look at the functions strcmp and strncmp.
You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).
0The standard library's
strcmpfunction compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."