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); }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With