0

My program takes in a student's last name, then first name, then midterm score 1, then midterm score 2, and lastly their final score. Based on the average of their midterm scores and their final score my program assigns each student with a grade (A-F).

Example input:

Barrett Edan 70 45 59 Bradshaw Reagan 96 97 88

Example of correct output:

Barrett Edan 70 45 59 F Bradshaw Reagan 96 97 88 A

My program instead outputs:

Barrett Edan 70 45 59 F Bradshaw Reagan 96 97 88 A Bradshaw Reagan 96 97 88 A

Why is this and what can I do to fix this?

while (!studentInfo.eof()) {
      float avgScore = 0;
      
      studentInfo >> lastName >> firstName >> midScore1 >> midScore2 >> finalScore;
      
      avgMid1 += midScore1;
      avgMid2 += midScore2;
      avgFinal += finalScore;
      avgScore = (midScore1 + midScore2 + finalScore)/3;
      
      if (avgScore >= 90) {
         grade = "A";
      }
      else if (avgScore >= 80 && avgScore < 90) {
         grade = "B";
      }
      else if (avgScore >= 70 && avgScore < 80) {
         grade = "C";
      }
      else if (avgScore >= 60 && avgScore < 70) {
         grade = "D";
      }
      else if (avgScore < 60) {
         grade = "F";
      }   
      
      newFile << lastName << "   " << firstName << "   " << midScore1 << "   " << midScore2 << "   " << finalScore << "   " << grade << endl;
      
      ++count;
   }
  • Explanation of the dupe: `studentInfo.eof()` doesn't get set until _after_ the first time it tries to read something and finds that the file is empty. At which point all subsequent reads fail, meaning that `lastName`, `firstName`, etc. retain their previous values and the rest of your loop continues on. – Nathan Pierson Nov 13 '22 at 05:38
  • Keep an eye on `avgMid1 += midScore1;` and the similar lines that follow. They don't look right. It looks like you might be summing up results across multiple students and reporting them as a single student. – user4581301 Nov 13 '22 at 05:56
  • Like this `while (studentInfo >> lastName >> firstName >> midScore1 >> midScore2 >> finalScore) { ... }` It's one of the great mysteries of C++, why do so many beginners prefer the incorrect `eof()` while loop, when the correct form is so simple. – john Nov 13 '22 at 09:35
  • Eh. It's not that surprising. It looks a lot like `while(moreWorkIsLeftToDo){ doWork; }`, which feels like a pretty natural way to structure a loop. The idiomatic version has you putting side effects in the loop condition. I think it makes sense once you know what it's doing, but it's not shocking to me that people gravitate toward the incorrect version. – Nathan Pierson Nov 13 '22 at 16:10

0 Answers0