C++ infinite EOF while loop, searched archive and didn’t find similar

  c++, eof, loops, while-loop

This is for a lab in my CS programming class. This is what I wrote:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int grade, avg, count = 0, total = 0;

    ifstream gradeFile;
    gradeFile.open("Lab9C.txt");

    gradeFile >> grade;

    while (!gradeFile.eof())
    {
        cout << "Grades: ";

        while (grade != 0)
        {
            cout << grade << " "; 
            count++;
            total = total + grade;
            avg = total / count;
            gradeFile >> grade;
        }

        cout << "Average: " << avg << endl;
    }

    gradeFile.close();
    return 0;
}

The program is supposed to read each line of a file and print all the grades from that file, then average the grades and print that. Right now It’s only printing: Grades: Average: 87 – on infinite repeat. I’ve tried moving my input statement to different areas, like within the first look and within the second one (initializing grade outside the loop with a grade = -1), and I get infinite loops no matter where I put that statement.

I looked at the other EOF questions on stackoverflow and they all appeared to be different questions. I’m pretty sure I formatted my eof correctly, since it’s formatted exactly like the other eof while loops I wrote for this class. So why is it infinitely repeating?

Source: Windows Questions C++

LEAVE A COMMENT