How do you read scanf until EOF in C?

JJRhythm picture JJRhythm · Sep 21, 2010 · Viewed 164.2k times · Source

I have this but once it reaches the supposed EOF it just repeats the loop and scanf again.

int main(void)
{
        char words[16];

        while(scanf("%15s", words) == 1)
           printf("%s\n", words);

        return 0;
}

Answer

codaddict picture codaddict · Sep 21, 2010

Try:

while(scanf("%15s", words) != EOF)

You need to compare scanf output with EOF

Since you are specifying a width of 15 in the format string, you'll read at most 15 char. So the words char array should be of size 16 ( 15 +1 for null char). So declare it as:

char words[16];