4

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!

Jonathan H
  • 7,591
  • 5
  • 47
  • 80
GDV
  • 65
  • 5
  • duplication ;) http://stackoverflow.com/questions/1065774/c-c-initialization-of-a-normal-array-with-one-default-value in here you find your answer :) – pkruk Aug 11 '14 at 09:13
  • For future questions: Please translate output and strings to English, it makes the code easier to understand. – iFreilicht Aug 11 '14 at 09:17
  • 1
    @neptyd: That is obviously not a duplicate – Lightness Races in Orbit Aug 11 '14 at 09:17
  • @iFreilicht I included a translation as a line comment whenever the program had anything in Spanish, even if that was irrelevant. If that is you were referring to... – GDV Aug 11 '14 at 09:27
  • Yes, that was what I meant. It probably was irrelevant (the code isn't really that complex), but it is easier to read now. – iFreilicht Aug 11 '14 at 09:29

1 Answers1

7

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;
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Thanks, this is exactly what I was looking for, but I'm not used to documentation yet. Thanks also to editors, the question seems much clearer now! – GDV Aug 11 '14 at 09:38
  • 1
    Also, is a good practice to clear the input buffer (include cin.clear()) in each iteration in the input loop? (to prevent this failbit problem, for instance) – GDV Aug 11 '14 at 09:46
  • @GDV yes, that's right - there's an example at http://en.cppreference.com/w/cpp/io/basic_ios/clear of how to use `clear` in a loop. – ecatmur Aug 11 '14 at 10:28