Cout/Cin with Arrays

In my programming class, we just learned about arrays yesterday. We had to create a test program that would receive 3 int values. My code is:

/* Andrew M
April 23, 2010
arrayProblem.cpp
Problems 2 and 7, pages 424 and 426
*/

//preprocessor directives
//allows usage of cin and cout
#include <iostream>

using namespace std;

int main ()
{ //begin main
system ("cls"); //clears the screen

//variable declarations
int threeValues [2];
int x;

for (x = 0; x < 3; x++)
{
cout << "Enter 3 integer values. " << endl;
cin >> threeValues [2];
}

cout << threeValues [0] << endl;
return 0;
} //end main

I get the following error message after I input the first value:

"Run-Time Check Failure #2 - Stack around the variable 'threeValues' was corrupted."

Could someone please tell me how to fix this?
Last edited on
Problem 1. Arrays in C++ use 0 based indexes. Your 3 variable array will have indexes 0, 1, and 2. Index 3 is out of bounds, and will cause a compile error.

Problem 2. cin >> threeValues [3]; Does not input 3 values. It only inputs a single value into index 3 (which we've already determined is out of bounds anyways). You will need a separate prompt for each index of the array, preferably done with a for() loop.
I editted my first post with the for() loop. The loop works, but when the I cout threeValues [0], it displays -858993460 and still shows the same error message...
try:
cout << "Enter 3 integer values. " << endl;

for (x = 0; x < 3; x++)
{
cin >> threeValues [x];
}
Last edited on
The for () loop you posted worked, and when I cout threeValues [0], it shows t he correct number. The only problem is that I still get the same error message....
When you initialize the array,

//variable declarations
int threeValues [2];

you are only giving it 2 elements, threeValues[0] and threeValues[1]. Thus when you run the for() loop and take in three integers, you get the error because you did not make a spot for the third.

Also, when you go to output the three numbers, use the same logic as the for() loop posted above, to cycle through and cout each element.
Topic archived. No new replies allowed.