【发布时间】:2014-06-23 16:10:21
【问题描述】:
我是 C++ 新手,编写了一些代码,但出现以下错误:
运行时检查失败 #2 - 变量“scores”周围的堆栈已损坏
是什么导致了这个错误?
这是我的代码:
#include <iostream> // Enables cout and endl
#include <string>
#include <sstream>
#include "stdafx.h"
using namespace std;
int getInput();
int main()
{
int scores[5];
int i;
int j;
int numberOfScores;
for (i = 0; i < 6; i++) // Sets all 5 elements of the array to zero
{
scores[i] = 0;
}
cout << "How many scores do you have to enter?\n" << endl;
cin >> numberOfScores;
for (j = 0; j < numberOfScores; j++) // Gather test scores and increases each array index as that score is entered
{
scores[getInput()] ++;
}
cout << "The number of zeros: " << scores[0] << endl;
cout << "The number of ones: " << scores[1] << endl;
cout << "The number of twos: " << scores[2] << endl;
cout << "The number of threes: " << scores[3] << endl;
cout << "The number of fours: " << scores[4] << endl;
cout << "The number of fives: " << scores[5] << endl;
return 0;
}
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 5.\n";
cin >> enteredScore;
if (enteredScore >= 0 && enteredScore <= 5)
{
return enteredScore;
}
else
{
cout << "Error! The range of scores is 0 to 5.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
return enteredScore;
}
}
【问题讨论】:
-
for (i = 0; i < 6; i++)应该是for (i = 0; i < 5; i++),否则它将访问分数[5],由于基于 0 的索引(0、1、2、3、4 是有效的,它被关闭了 1,这就是您请求存储的 5 个元素)。 -
请先调试后再问!
标签: c++ arrays indexoutofboundsexception