开发者

Never reaching eof using ifstream (cpp)

I am reading text from a text file, but I never reach eof, which results in an endless loop.

Here's what I wrote

static ifstream inF;
inF.open(file,ifstream::in);
cin.rdbuf(inF.rdbuf());
while (inF.good() && !inF.eof())
{
    addStudent(students);
}
if (inF.is_open())
{
    inF.close();
    inF.clear();
}

Every Iteration of the loop I call addStudents, which handles only one line. That works fine for me. Basically I rad lines in the form of D 98 76.5 66 45 (Possibly) 12000 here's the code:

static void addStudent(vector<Student*> students)
{
char institution;
unsigned short id;
double gAverage, pGrade, salary;
cin >> institution;

switch (institution)
{
case ALICE:
    cin >> id >> gAverage >> salary;
   开发者_开发技巧     students.push_back(new Student(institution,id,gAverage,salary));
        return;
case BOB:
    cin >> id >> gAverage >> salary;
    students.push_back(new Student(institution,id,gAverage,salary));
    return;
case COLIN:
    cin >> id >> gAverage >> pGrade >> salary;
    students.push_back(new                  CollegeStudent(institution,id,gAverage,pGrade,salary));
    return;
case DANNY:
cin >> id >> gAverage >>  pGrade >> salary;
    students.push_back(new CollegeStudent(institution,id,gAverage,pGrade,salary));
    return;
}
}

When I get to the end of the file the loop keeps running, and addStudents (which returns void) does nothing. Any Ideas why? Thanks!


Your file stream may share it's stream buffer with cin, but it doesn't share it's flags. So when you read using cin's operator>>, and it the reaches end of the file, cin sets it's own eof flag, but it doesn't set the flag in your ifstream(how could it? it has no knowledge of it).

This is an awfully silly way to read a file, why are you doing it like that? Why don't you just pass an istream reference into your addStudent function and read from that?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜