What happens when the >> operator tries to enter a value greater than the variable can contain?

I pull the numbers from the text file and fill it with an array of type int.

I insert the values ​​into the array, iterating over the .txt file with these lines of code (where k is the number of numbers in the TXT file):

for (int j = 0; j < k; j++)
  inputFile >> tab[j];

When the numbers in the text file are less than 2,147,483,647, which is the maximum size of an integer type, everything goes smoothly.

When a number is greater than this, the program, I assume, overflows and does not insert it, but after that also cannot insert any number.

What causes it not to insert more numbers after overflow?

+4
source share
3

std::istream& std::istream::operator>>(std::istream&, int&), cppreference :

FormattedInputFunction. -, , , std::num_get::get()

...

, failbit. , , std::numeric_limits<T>::max() std::numeric_limits<T>::min() . ( ++ 11)

, , .

FormattedInputFunctions . - false, .

- false, , , , .


, :

  • , int.
  • int, , , int.
  • , , .
  • , .

, failbit , , int istream, .

, failbit std::basic_ios::clear. clear, failbit, , .

+5

, , , failbit. ( [istream.formatted.arithmetic]/3):

operator>>(int& val);

, [...]:

iostate err = ios_base::goodbit;
long lval;
use_facet<numget>(loc).get(*this, 0, *this, err, lval);
if (lval < numeric_limits<int>::min()) {
    err |= ios_base::failbit;
    val = numeric_limits<int>::min();
}
else if (numeric_limits<int>::max() < lval) {
    err |= ios_base::failbit;
    val = numeric_limits<int>::max();
}
else
    val = static_cast<int>(lval);
setstate(err);

, , "", , .

+5

Undefined. Arithmetic overflows can be ignored silently or can cause an increase in the signal that terminates the program, depending on the quality of implementation.

-5
source

Source: https://habr.com/ru/post/1666658/


All Articles