访问数组时出错 - 变量'得分'周围的堆栈已损坏

-6 c++ arrays indexoutofboundsexception

我是C++的新手,并编写了一些代码,其中我收到以下错误:

运行时检查失败#2 - 变量'得分'周围的堆栈已损坏

导致此错误的原因是什么?

这是我的代码:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

yiz*_*lez 5

看来这个宣言:

int scores[5];
Run Code Online (Sandbox Code Playgroud)

是不正确的.这将创建一个包含5个数字的数组scores[0-4],但是,您经常引用的索引是整个程序中数组score[5]第六个元素.我建议换到

int scores[6];
Run Code Online (Sandbox Code Playgroud)