Code is putting number at end of array for unknown reason

    I need to read a file of just students marks into an array. I can do everything except when I check the array there is a large extra number at the end that doesn’t look like its related to the students mark file. The text file is one column and the first number is how many units the student is doing, then the students ID, then its the marks. I just need to ignore the student ID at the moment. The start of the file looks like this:
    2
    S123123123
    62
    70
    4
    S111111111
    96
    67
    88
    88
    So the 2 and 4 relates to how many marks I need to read for each student.

    Here is my code:

    #include <iostream> #include <fstream> #include <string>   #include <iomanip> using namespace std;  int main() {     //Creating  Array     const int SIZE = 100;     int marksArray[SIZE];      //Reading file     ifstream inFile("marks.txt");      int numberUnits;     string studentID;     int runningTotal = 0;     while (!inFile.eof())     {         inFile >> numberUnits;         inFile >> studentID;         for (int i = 0; i < numberUnits; i++)     {         inFile >> marksArray[runningTotal++];                       }      }  //Testing results cout << runningTotal << endl; for (int k = 0; k <= runningTotal; k++) {     cout << marksArray[k] << " "; }  cout << "number of marks: " << runningTotal; cout << endl << marksArray[23]; return 0; 

    }

    So my results is "23" for the number marks (there’s only suppose to be 22). The array looks like 62 70 96 67 88 88 ….and it continues for all 22 marks except at the end there is a final element "1877944186" I have no idea why it is there, pls help

    Professor Asked on October 18, 2020 in Android langue.
    Add Comment
    1 Answer(s)

      simply replace this line:

      for (int k = 0; k <= runningTotal; k++) 

      with :

      for (int k = 0; k < runningTotal; k++) 
      Professor Answered on October 18, 2020.
      Add Comment

      Your Answer

      By posting your answer, you agree to the privacy policy and terms of service.