Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting EOF in C

Tags:

c

stdio

I am using the following C code to take input from user until EOF occurs, but problem is this code is not working, it terminates after taking first input. Can anyone tell me whats wrong with this code. Thanks in advance.

float input;  printf("Input No: "); scanf("%f", &input);  while(!EOF) {     printf("Output: %f", input);     printf("Input No: ");     scanf("%f", &input); } 
like image 714
itsaboutcode Avatar asked Sep 15 '09 18:09

itsaboutcode


People also ask

Can Scanf detect 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.

How do I find my EOF character?

The EOF in C/Linux is control^d on your keyboard; that is, you hold down the control key and hit d. The ascii value for EOF (CTRL-D) is 0x05 as shown in this ascii table . Typically a text file will have text and a bunch of whitespaces (e.g., blanks, tabs, spaces, newline characters) and terminate with an EOF.

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.


2 Answers

EOF is just a macro with a value (usually -1). You have to test something against EOF, such as the result of a getchar() call.

One way to test for the end of a stream is with the feof function.

if (feof(stdin)) 

Note, that the 'end of stream' state will only be set after a failed read.

In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.

like image 123
CB Bailey Avatar answered Sep 19 '22 15:09

CB Bailey


EOF is a constant in C. You are not checking the actual file for EOF. You need to do something like this

while(!feof(stdin)) 

Here is the documentation to feof. You can also check the return value of scanf. It returns the number of successfully converted items, or EOF if it reaches the end of the file.

like image 37
A. Levy Avatar answered Sep 18 '22 15:09

A. Levy