Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read scanf until EOF in C?

Tags:

c

eof

scanf

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; } 
like image 782
JJRhythm Avatar asked Sep 21 '10 20:09

JJRhythm


People also ask

Does scanf read EOF?

scanf returns EOF if end of file (or an input error) occurs before any values are stored. If any values are stored, it returns the number of items stored; that is, it returns the number of times a value is assigned by one of the scanf argument pointers.

What does EOF in C mean?

In computing, end-of-file (EOF) is a condition in a computer operating system where no more data can be read from a data source.


1 Answers

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]; 
like image 179
codaddict Avatar answered Oct 14 '22 10:10

codaddict