I'm learning C++, doing some easy examples, and found this odd behavior. When filling the elements of an array of integers, if any of the elements is set to something greater than 2147483647 (which I believe is the maximum integer value?), the rest of the elements in the array are set to that exact number, every one of them.
I understand that if one element goes beyond its type limit, the compiler caps it to that limit, but I can't get why it does the same thing with the other items, without even asking the user to fill them.
Here's a simple test I've run:
#include <iostream>
using namespace std;
int main()
{
int test[5];
int num = 0;
for (int i=0; i<5; i++)
{
cout << "Enter the number in position " << i << endl;
cin >> num;
test[i] = num;
}
cout << "Values in the array: " <<endl;
for (int i=0; i<5; i++)
cout << test[i] << endl;
}
Thanks for reading, commenting, and helping!
Documentation of std::istream::operator>>
:
If extraction results in the value too large or too small to fit in
value
,std::numeric_limits<T>::max()
orstd::numeric_limits<T>::min()
is written andfailbit
flag is set.
Once the failbit
flag is set, subsequent input operations will have no effect, meaning that aux
is left unchanged.
If you want to continue extracting items after conversion failure, you need to clear
failbit:
cin.clear();
cin >> aux;
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