Search code examples
cif-statementfgetsstrcmp

strcmp with fgets doesnt work as it should


I want to test if a string which I read with fgets() is "new" or "repeat". If it is repeat, it works how it should, but if it is "new" it doesn't work. Anyone knows why?

    char repeatornew[7];
    fgets(repeatornew,7,stdin);
    if(strcmp("repeat",repeatornew) == 0)
    {
        puts("repeat it.");
    }
    else
    {

        if(strcmp("new",repeatornew) == 0)
        {
            puts("new.");
        }
        else
        {
            printf("Please repeat the input! \n");

        }
    }

Solution

  • The behaviour of fgets() is:

    Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

    If "repeat" is entered repeatornew does not contain the newline character as it only has room for 6 characters plus the terminating null character. If "new" is entered then repeatornew will contain the newline character and the strcmp() will fail.

    To confirm this behaviour print the content of repeatornew after the fgets():

    if (fgets(repeatornew,7,stdin))
    {
        printf("[%s]\n", repeatornew);
    }
    

    To correct, increase the size of the repeatornew array and include the newline character in the string literals for comparision or remove the newline character from the repeatornew array if it is present.