Search code examples
cif-statementc-stringsstring-comparison

How can I do an `if` check if the typed word is equal to some word in a string list in C?


How can I do an if check if the typed word is equal to some word in a string list in C? Example:

#include <stdio.h>

int main(){

char input[20];
char* strings[] = {"apple","banana"};

printf("try to hit one of my favorite fruits:\n");
scanf("%s", input);

if(input == strings[]){
     printf("you got it right %s is one of my favorite fruits!", input);
}else{
    printf("you missed");
     }
}


Solution

  • I guess this is what you're looking for.

    #include<stdio.h>
    #include<string.h> //you need string.h to use strcmp()
    
    int main(){
    
    char input[20];
    char* strings[] = {"apple","banana"};
    
    printf("try to hit one of my favorite fruits:\n");
    scanf("%s", input);
    for(int i=0;i<2;i++){ //2 is the length of the array
    if(strcmp(input,strings[i])==0){ //strcmp() compares two strings
         printf("you got it right %s is one of my favorite fruits!", input);
         return 0;
    }
    }
    printf("you missed");
    }