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);
}
as a starting point you could try replacing
with
EOF
is a constant in C. You are not checking the actual file for EOF. You need to do something like thisHere 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.Another issue is that you're reading with
scanf("%f", &input);
only. If the user types something that can't be interpreted as a C floating-point number, like "pi", thescanf()
call will not assign anything toinput
, and won't progress from there. This means it would attempt to keep reading "pi", and failing.Given the change to
while(!feof(stdin))
which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value ofinput
and printing the prompt, but the program would never process any new input.scanf()
returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something likechar string[100];scanf("%99s", string);
. This will remove the next string from the input stream (up to 99 characters, anyway - the extrachar
is for the null terminator on the string).You know, this is reminding me of all the reasons I hate
scanf()
, and why I usefgets()
instead and then maybe parse it usingsscanf()
.You want to check the result of scanf() to make sure there was a successful conversion; if there wasn't, then one of three things is true:
Example:
EOF
is just a macro with a value (usually -1). You have to test something againstEOF
, such as the result of agetchar()
call.One way to test for the end of a stream is with the
feof
function.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.