Search code examples
cfgetsstrcmp

using fgets and strcmp in C


I'm trying to get a string input from the user and then run different functions depending on the input they've entered.

For example, say I asked, "What is your favorite fruit?" and I want the program to comment depending on what they enter...I'm not sure how to do this. Here's what I have so far:

#include <stdio.h>
#include <string.h>

char fruit[100];

main() {
    printf("What is your favorite fruit?\n");
    fgets (fruit, 100, stdin);
    if (strcmp(fruit, "apple")) {
        printf("Watch out for worms!\n");
    }
    else {
        printf("You should have an apple instead.\n");
        }

}

When I run the program, no matter what I enter, it never does the else statement.

Thanks for your help!


Solution

  • Note two things in your code:

    1. fgets keeps the trailing '\n'. the associated char in fruit should be replaced with a '\0' before comparing with the string "apple".
    2. strcmp return 0 when two strings are the same, so the if clause should be changed based on what you mean.(The fruit and "apple" be equivalent in the if clause)
    3. Standard usage of C main function is int main(){ return 0;}

    The revised code:

    #include <stdio.h>
    #include <string.h>
    
    char fruit[100];
    
    int main() {
        printf("What is your favorite fruit?\n");
        fgets (fruit, 100, stdin);
        fruit[strlen(fruit)-1] = '\0';
        if (strcmp(fruit, "apple") == 0) {
            printf("Watch out for worms!\n");
        }
        else {
            printf("You should have an apple instead.\n");
        }
        return 0;
    }