Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array auto-filling itself in C++

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!

like image 864
GDV Avatar asked Mar 19 '23 18:03

GDV


1 Answers

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() or std::numeric_limits<T>::min() is written and failbit 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;
like image 117
ecatmur Avatar answered Mar 29 '23 05:03

ecatmur