I understand that cin.eof()
tests the stream format. And while giving input, end of character is not reached when there is wrong in the input. I tested
For an input stream to enter the EOF state you have to actually make an attempt to read past the end of stream. I.e. it is not enough to reach the end-of-stream location in the stream, it is necessary to actually try to read a character past the end. This attempt will result in EOF state being activated, which in turn will make cin.eof()
return true.
However, in your case you are not only not doing that, you (most likely) are not even reaching the end of stream. If you input your 10
from the keyboard, you probably finished the input by pressing the [Enter] key. This resulted in a new-line character being added to the input stream. So, what you are actually parsing with >>
operator in this case is actually a 10\n
sequence. Since you requested an int
value from the stream, it only reads the numerical characters from the stream, i.e. it reads 1
and 0
, but it stops at \n
. That \n
remains in the stream. You never read it. So, obviously, your code never reaches the end-of-file position in the stream. You have to reason to expect cin.eof()
to become true
in such case.
Adding to the previous answer: After reading your input (like 10), you are not at end-of-file, as you can easily type some more. How is the system to know that you will not?
When reading your second input (12a), it correctly reads all the digits that can be part of an integer. The letter 'a' cannot, so it is left for some possible later input. For example, you can read all parts of 12a with this code
int i; char c;
cin >> i >> c;