-3

I was asked to obtain text and numbers from a .txt file to a C++ program. What I don't know is the number of students I will be sorting their grades out so I use a while loop with the condition of !fin.eof() Code:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
ifstream fin;
fin.open("grades.txt");
cout << "Name\t\t\t" << "Midterm\t" << "HMAvg\t" << "Final\t" << "Average\t" << "Grade" << endl;

while(!fin.eof())
{
    string name;
    double mdtrm, final, hw, shw=0, ahw=0, avg;
    char grade;

    getline(fin, name);

    fin >> mdtrm;
    fin >> final;

    for(int i=0; i<5; i++)
    {
        fin >> hw;
        shw = shw+hw;
    }

    ahw = shw/5;
    avg = ((mdtrm*0.3)+(final*0.4)+(ahw*0.3));

    if(avg>=90 && avg<=100)
        grade = 'A';
    else if(avg>=80 && avg<90)
        grade = 'B';
    else if(avg>=70 && avg<80)
        grade = 'C';
    else
        grade = 'F';

    cout << name << "\t" << mdtrm << "\t" << ahw << "\t" << final << "\t" <<  avg << "\t" << grade << endl;
}

fin.close();

system("pause");

return 0;
}

It infinitely loops. I made sure the .txt file is ok What's wrong with my code ?

  • 1
    Read [this](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) for a start. And [this](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Baum mit Augen Jan 18 '15 at 17:12
  • I predict that one of the input operation fails, and leaves the stream in failed state (`fin.fail() == true`). After that, all subsequent operations fail immediately, and you aren't making any progress. – Igor Tandetnik Jan 18 '15 at 17:12
  • What did the debugger tell you? – πάντα ῥεῖ Jan 18 '15 at 17:20
  • @πάνταῥεῖ There was no error but the program kept looping after running – user2834298 Jan 18 '15 at 17:43
  • 2
    @user2834298 That wasn't my question. What did you notice when you're stepping through the program with the debugger line by line? – πάντα ῥεῖ Jan 18 '15 at 17:50

1 Answers1

0

The problem was with the getline function where it is not stable to be used inside loops. Thanks everyone.