Automatic array filling in C ++

I learn C ++ by making some simple examples and discover this weird behavior. When filling in the elements of an array of integers, if any of the elements is set to something greater than 2147483647 (what, in my opinion, is the maximum integer value?), The rest of the elements in the array are set to this exact number, each one of them.

I understand that if one element goes beyond its type limit, the compiler limits it to this limit, but I cannot understand why it does the same with other elements, without even asking the user about its filling.

Here is a simple test that I performed:

#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!

+4
1

std::istream::operator>>:

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

failbit , , , aux .

, clear failbit:

    cin.clear();
    cin >> aux;
+7

All Articles