For the error of input: Just remember C language return EOFand NULL, and C++ return all false.
Number, non-white
character, white
string
C
scanf return EOF
getchar return EOF
fgets return NULL
c++
cin return false
cin return false
cin.getline return false
When you can’t continue input, you need to know if it’s end of file or fail. In
C language, you can use feof and ferror function, in C++, you can use
cin.eof(), cin.fail() or cin.bad() three functions. cin.bad() means serious
system error happens, and input buffer can’t be consistent and can’t be
recoveried anymore.
When failbit or badbit are set. fail() return false, So you need to judge it by
bad() again if this information is important for you. Usually, bad() is not
use very often.
eofbit is interesting topic. when you reach(not read) the "logical end-of-file",
it will not be set, It’s set by a read function, not by position
Instead, You can use std::ifstream::peek() to check for the "logical
end-of-file".
eof is set by last read EOF position When you read EOF position,
failbit is set and eof is set too. So If EOF is set, failbit must set too. If only
failbit is set, it means that input error happen. Under these two conditions,
istream will return false by operator bool.
In http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool . You
can see eofbit are true and failbit are false, operator bool return
true. I don’t’ know when it will happen. eof() function returns"true" after the program attempts to read past the endof the file. But when read action set eofbit, it will set failbit at
the sametime, so bool operator will return false because failbit are
set.
How do you know if you read an incorrect input word, or if you are at
the end of the file? This is when you use cin.eof() or feof() in C
language.
you can use clear() and setstate() to set the states, Why? It’s just
depends on what the program is trying to accomplish. It provides
a means for you to change the state. setstate() is different with
clear(), clear() clear all the status bit. but setstate just set specific
bit.
You can use exceptions() method to control if exceptions will throw, when
the eofbit, failbit and badbit is set.
setstate() is to provide a means for input and output functions to change the
state. For end user, we don’t use it very often. We just use clear()
more.
for rdstate() it will return all the bit value, then you can use & to
certain bit( such as failbit) to check if the bit has been set. But here,
you can use fail() directly, so we don’t use this function very often.
clear() function is very important, when cin.fail() return true, youhave to use clear(), otherwise all he below cin operation will notwork. See below example.