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?
if(strcmp(aString, bString) == 0){
//strings are the same
}
godspeed
You can't compare array of characters using ==
operator. You have to use string compare functions. Take a look at Strings (c-faq).
The standard library's
strcmp
function 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."
if(!strcmp(favoriteDairyProduct, "cheese"))
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Source: Stackoverflow.com