0

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");

        }
    }
Peter
  • 1,679
  • 2
  • 31
  • 60
  • 1
    Define "doesn't work". – Oliver Charlesworth Jun 25 '13 at 08:13
  • If I type "repeat" it does puts("repeat it."); but if i type "new" if does printf("Please repeat the input! \n!); So strcmp("new",repeatornew) is never 1 even when I type new – Peter Jun 25 '13 at 08:16
  • @user2514164 If you type "repeat" Your program will also read the newline produced when you hit the enter key. So your program gets "repeat\n". The last "\n" might be read the next loop if you don't read it with the first fgets() call (And think about how much room there is in your array, when this happens, maybe there is room for the \n if you input "new\n") – nos Jun 25 '13 at 08:24

1 Answers1

4

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.

hmjd
  • 120,187
  • 20
  • 207
  • 252