How to compare strings in an if statement?

I want to check and see if a variable of type โ€œcharโ€ can be compared with a regular string of type โ€œcheeseโ€ for comparison, for example:

#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 really want to do is much longer than that, but this is the main part that I'm stuck on). So, how would you compare two lines in C?

+9
source share
6 answers

You are looking for the strcmp or strncmp from string.h .

Since strings are just arrays, you need to compare each character, so this function will do this for you:

 if (strcmp(favoriteDairyProduct, "cheese") == 0) { printf("You like cheese too!"); } else { printf("I like cheese more."); } 

Further reading: strcmp at cplusplus.com

+24
source

Take a look at the strcmp and strncmp functions .

+4
source
 if(strcmp(aString, bString) == 0){ //strings are the same } 

Godspeed

+4
source

You cannot compare an array of characters with the == operator. You should use string comparison functions. See Lines (c-faq) .

The strcmp standard library strcmp compares two strings and returns 0 if they are identical, or a negative number if the first line in alphabetical order is โ€œless thanโ€ the second line or a positive number if the first line is more. โ€

+3
source
 if(!strcmp(favoriteDairyProduct, "cheese")) { printf("You like cheese too!"); } else { printf("I like cheese more."); } 
+1
source

hi, I just want to ask how to print something using a string, for example, if I am a user, I want to write the word January and print something that is 31 days in January, like this

if (month == 'January') printf ("JANUARY HAS 31 DAYS")

ANYTHING AS IT IS NECESSARY ONLY ONE OF THE CHARACTER

this is my sample code

month symbol

printf ("Enter the name of the month and check how many days"); scanf ("% c", month);

if (month == 'january') {

printf ("JANUARY HAS 31 DAYS);}

LIKE WHAT I JUST WANT TO MAKE THE WORD JANUARY, AND THIS PRINTES LIKE THAT ANYONE CAN HELP ME WITH MY PROBLEM

-1
source

Source: https://habr.com/ru/post/902078/


All Articles