为什么当我到达我的 2D 阵列时它会崩溃?out_of_range

Why does it crash when I reach my 2D Array? out_of_range

本文关键字:崩溃 out of range 我的 阵列 2D 为什么      更新时间:2023-10-16
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <stdlib.h>
using namespace std;
int gradeExam(string answerKeyARR[]);

int main()
{
    const int QUESTIONS = 10;
    const int MAX_STUDENTS = 250;
    ifstream inFile;
    ofstream outFile;
    inFile.open("grade_data.txt");
    outFile.open("grade_report.txt");
    string ansKey;
    inFile >> ansKey;
    string answerKeyARR[QUESTIONS];
//Loop for storing each answer into an array rather than all in a single string.
    for (int j = 0; j < QUESTIONS; j++)
    {
        answerKeyARR[j] = ansKey.substr(j,1);
    }
    int i = 0;
    int numStudents = 0;
    string studentAnswers[MAX_STUDENTS];
//Loop to read in all answers into array and count number of students.
    while (!inFile.eof())
    {
        inFile >> studentAnswers[i];
        numStudents++;
        i++;
    }
//WHY DOES IT CRASH HERE?!
    string studentAnswersARR[numStudents][QUESTIONS];
    for (int k = 0; k < numStudents; k++)
    {
        for (int l = 0; l < QUESTIONS; l++)
        {
            studentAnswersARR[k][l] = studentAnswers[l].substr(l,1);
cout << studentAnswersARR[k][l];
        }
    }
    inFile.close();
    outFile.close();
    return 0;
}

好的,所以基本上一旦它到达它删除子字符串的部分,它就会崩溃。它非常适合检索答案键答案,那么为什么当它到达这一点时它会崩溃呢?这仍然是基本编码 2 的 WIP。此外,当我将变量"l"更改为位置 0 时,它可以工作。什么给?

您的代码存在多个问题,可能会导致问题。

首先,输入循环未正确绑定。 它应该在 MAX_STUDENTS 停止,但您无法检查此限制。

其次,不要使用eof()来检查文件的结尾。 SO上有很多帖子在讨论这个问题。

while (!inFile && i < MAX_STUDENTS)
{
    inFile >> studentAnswers[i];
    numStudents++;
    i++;
}

下一个问题是您在问题中强调的那一行。 它可能由于堆栈空间耗尽而崩溃。 但是您拥有的代码使用非标准的C++扩展,一旦您这样做了,那么关于该行在内部真正做什么的规则取决于编译器供应商。

因此,为了通过使用标准C++来缓解这种情况,可以执行以下操作:

#include <vector>
#include <string>
#include <array>
//...
    std::vector<std::array<std::string, QUESTIONS> > 
                               studentAnswersARR(numStudents);