2015-02-06 32 views
0
#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時,它可以工作。是什麼賦予了?爲什麼當我到達2D陣列時會崩潰? out_of_range

+1

'串studentAnswersARR [numStudents] [問題];'這不是標準C++。它不應該編譯。如果它編譯,它是一個非標準擴展,其規則由編譯器供應商決定。 – PaulMcKenzie 2015-02-06 23:25:27

+0

哦,它不是標準的C++,因爲你使用一個變量來表示數組中的項目數。數組聲明時必須使用編譯時間常量。 – PaulMcKenzie 2015-02-06 23:29:52

回答

0

您的代碼存在多個可能導致問題的問題。

首先,您的輸入循環沒有正確界定。它應該停止在MAX_STUDENTS,但您未能檢查此限制。

其次,不要用eof()來檢查文件的結尾。在討論這個問題上有很多帖子。

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); 
+0

感謝您的快速響應!我已經做出了您所建議的更改,但我不確定自己是否真正瞭解數組的新語法。而且,它仍然崩潰。 – liquidTurtle 2015-02-07 00:18:36

+0

我不認爲你需要將'ansKey'分解爲另一個向量。您可以按原樣使用該字符串,而無需執行此操作。 – PaulMcKenzie 2015-02-07 00:30:17

+0

我之後需要將它分開,因爲我必須比較學生的所有答案,並將所有錯誤/正確的答案加起來以返回他們的分數。 – liquidTurtle 2015-02-07 00:39:04

相關問題