const int MAX = 1000;
int a[MAX]; // allocated on call stack
int n = 0;
//--- Read into the array
while (cin >> a[n]) { // can overflow array
n++;
}
//--- Write out the array
for (int i=0; i<n; i++) {
cout << a[i] << endl;
}
You can check to see if MAX has been exceeded in the input loop, but then what
should you do? Giving an error message and stopping doesn't solve anyone's problem.
Continuing with only part of the data is worse because it will
give the wrong answer. The way to handle this is to make the array bigger!
int max = 10; // Current allocated max size. int* a = new int[max]; // Allocate space in heap. int n = 0; // Current number of elements. //--- Read into the array while (cin >> a[n]) { n++; if (n >= max) { max = max * 2; // Double the previous size. int* temp = new int[max]; // Allocate new, bigger array. for (int i=0; i<n; i++) { temp[i] = a[i]; // Copy old array to new array. } delete [] a; // Free old array memory. a = temp; // Now a points to new array. } } //--- Write out the array etc.
The solution to these, and other, problems is in the STL vector class.