Search code examples
cstdio

Detecting EOF in C


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. What's wrong with this code?

float input;
 
printf("Input No: ");
scanf("%f", &input);
    
while(!EOF)
{
    printf("Output: %f", input);
    printf("Input No: ");
    scanf("%f", &input);
}

Solution

  • 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.