I\'m pulling numbers from a text file and filling an array of type int with them.
I\'m inserting the values into the array while looping through the .txt file with t
On std::istream& std::istream::operator>>(std::istream&, int&), cppreference says:
Behaves as a FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, extracts an integer value by calling
std::num_get::get()
...
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value,
std::numeric_limits
or::max() std::numeric_limits
is written and failbit flag is set. (since c++11)::min()
It's not normative, but it does provide a decent summary of what is happening here.
FormattedInputFunctions will construct a sentry from the stream and check the value. If the sentry object evaluates as false
, then no input is performed.
The sentry object will evaluate as false
if, among other situations, the stream being operated on has the failbit set.
So, what's happening is this:
int
data type. int
passed into its function is set to the maximum possible value an int
can store.You can detect these overflow errors by checking the failbit and value of the integer after the read operation you are performing, as mentioned in the accepted answer to the question Read int from istream, detect overflow.
You can recover from these errors by unsetting the failbit with std::basic_ios::clear. Following a call to clear
which unsets the failbit, further reads will behave as you expect.