This example uses the bit operators & and ~: Operator ~ returns the bitwise complement of its
argument. Thus, the following expression returns a temporary value that has all bits set except
failbit:
~ios::failbit
Operator & returns a bitwise “and” of its operands. Only the bits set in both operands remain set.
Applying bitwise “and” to all currently set flags (rdstate()) and to all bits except failbit retains
the value of all other bits while failbit is cleared.
Streams can be configured to throw exceptions if certain flags are set with clear() or
setstate() (see Section 15.4.4, page 762). Such streams always throw an exception if the corresponding
flag is set at the end of the method used to manipulate the flags.
Note that you always have to clear error bits explicitly. In C, it was possible to read characters
after a format error. For example, if scanf() failed to read an integer, you could still read the
remaining characters. Thus, the read operation failed, but the input stream was still in a good state.
This is different in C++. If failbit is set, each following stream operation is a no-op until failbit
is cleared explicitly.
In general, the set bits reflect only what happened sometime in the past: If a bit is set after an
operation, this does not necessarily mean that this operation caused the flag to be set. Instead, the
flag might have been set before the operation. Thus, if it not known whether an error bit is set, you
should call clear() before an operation is executed to let the flags tell you what went wrong. Note
however, that operations may have different effects after clearing the flags. For example, even if
eofbit was set by an operation, this does not mean that after clearing eofbit the operation will set
eofbit again. This can be the case, for example, if the accessed file grew between the two calls.