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 this on my MSV C++ 2010 and am not understanding the strange results. No matter what I give the input, I am getting Format Error message that is present in the program.
#include <iostream>
using namespace std;
int main()
{
int i;
cin>> i;
if(!cin.eof())
{
cout<< "\n Format Error \n";
}
else
{
cout<< "\n Correct Input \n";
}
getchar();
return 0;
}
Results I expected:
Values for i =
Could someone explain where I am going wrong. Thanks.
EOF instead is a negative integer constant that indicates the end of a stream; often it's -1, but the standard doesn't say anything about its actual value. C & C++ differ in the type of NULL and '\0' : in C++ '\0' is a char , while in C it's an int ; this because in C all character literals are considered int s.
EOF is detected when there's no more data to read. When you write to a file, you don't need to write a special character; closing the file means that the file has a fixed size and EOF will be reported when reading and the read offset reaches the end of the file.
get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found.
std::cin.eof()
tests for end-of-file (hence eof), not for errors. For error checking use !std::cin.good()
, the built-in conversion operator (if(std::cin)
) or the boolean negation operator (if(!std::cin)
).
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.
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