21

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?

Jason Orendorff
  • 42,793
  • 6
  • 62
  • 96
lakam99
  • 575
  • 4
  • 9
  • 24
  • By the way, using scanf() like that is a very serious bug. If you enter a word longer than 30 characters, your program will probably crash. fgets() is safer. – Jason Orendorff Sep 27 '12 at 11:55

5 Answers5

36

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

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
Kaslai
  • 2,445
  • 17
  • 17
5
if(strcmp(aString, bString) == 0){
    //strings are the same
}

godspeed

Trevor Arjeski
  • 2,108
  • 1
  • 24
  • 40
4
if(!strcmp(favoriteDairyProduct, "cheese"))
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
SANTHOSH.SJ
  • 343
  • 1
  • 4
  • 7
4

Have a look at the functions strcmp and strncmp.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77
3

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."

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186