Search code examples
cloopscomparestrcmp

C :How to compare two strings and find a word i need?


Its not complete, but in doesnt print anything

char *fruit[] = {"rasberry", "cherry"};
char *veg[] = {"salad", "tomato"};
char word;


printf("Print a veg or a fruit \n");
scanf("%s", &word);


for (int i = 0; i < strcmp(fruit, veg ); i++)
{
    if (word == fruit[i])
        printf("Its fruit!");
}

how to compare it?


Solution

  • Ok after a bit more clarification what is needed, try something like this:

        char *fruit[] = {"rasberry", "cherry"};
        char *veg[] = {"salad", "tomato"};
        char word[100]={0};
    
    
        printf("Print a veg or a fruit \n");
        scanf("%s", word);
    
        // Check fruit
        for (int i = 0; i < 2; i++)
        {
            if (strcmp(word,fruit[i])==0)
            {
                printf("Its fruit \n");
            }
        }
        // Check veg
        for (int i = 0; i < 2; i++)
        {
            if (strcmp(word,veg[i])==0)
            {
                printf("Its veg \n");
            }
        }