vendredi 27 novembre 2015

C++ While loop running after EOF

Just need some help with an assignment. My EOF While loop continues to run even after the file is complete. So when the first loop runs I'll enter StudID 101 & 102 with scores. Then in the output (not txt file) it will display 101, 102, & 103. Can someone point out why this happens?

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

int main() {

    int studID, quizGrade;
    int i, studCount = 0;
    fstream File("Quizzes.txt");

    cout << "Enter a 0 for no students \n";
    cout << "Enter student ID: \n";
    cin >> studID;
    cout << endl;

    File.open("Quizzes.txt", ios::out); //Open file
    File.trunc;                         //Erase contents 
    File.close();                       //Close file to save changes
    File.open("Quizzes.txt", ios::out); //Open file for pgm to use

    while (studID != 0)
    {   
        File << studID << "\t";

        for (i = 0; i < 4; i++)
        {
            cout << "Enter quiz grade: ";
            cin >> quizGrade;
            if (quizGrade < 0 || quizGrade > 100)
            {
                cout << "Invalid quiz grade\n";
                system("pause");
                return 0;
            }
            File << quizGrade << "\t";
        }
        File << "\n";
        cout << endl;
        cout << "Enter a 0 for no more students or enter student ID\n";
        cin >> studID;
        studCount++;
    }
    File.close();

    int quizGrade1, quizGrade2, quizGrade3, quizGrade4, totalQuizPts, classTotal = 0;
    int y = 0;
    double quizAvg, classAvg;

    File.open("Quizzes.txt", ios::in);

    while (!File.eof())
    {
        for (y = 0; y < studCount; y++)
        {
            File >> studID;
            File >> quizGrade1;
            File >> quizGrade2;
            File >> quizGrade3;
            File >> quizGrade4;
            totalQuizPts = quizGrade1 + quizGrade2 + quizGrade3 + quizGrade4;
            quizAvg = double(totalQuizPts) / 4;

            cout << studID << " average quiz grade is: " << setprecision(2) << fixed << quizAvg << endl;
            classTotal += totalQuizPts;
        }

    }

    classAvg = double(classTotal) / (y*4);
    cout << "The class average is " << classAvg << endl;


    system("pause");
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire