0
void StudentArrayV4::add_from(istream &infile) {
    Student temp;
    string name;
    getline(infile, name, ':');
    temp.set_name(name);
    int id;
    infile >> id;
    temp.set_id(id);
    double score;
    while (infile >> score)
    {
        temp.add_exam_score(score);
    }
    add(temp);
    if (name != "")
    {
        infile.ignore();
        infile.clear();
    }
}

int StudentArrayV4::add_all_from( istream& infile ) {
    while (!infile.eof())
    {
        add_from(infile);
        number_of_students++;
    }
    return number_of_students;
}

I want to use the function add_all_from to add Students to the array but it gets in an infinite loop. I don't understand why eof() doesn't work in this case.

001
  • 13,291
  • 5
  • 35
  • 66
  • What is your understanding of how `eof` works, and why? – Scott Hunter Mar 03 '22 at 13:33
  • 1
    Maybe change the function to return `false` when there is no more data. Ex: `if (!getline(infile, name, ':')) return false;` – 001 Mar 03 '22 at 13:35
  • And then change `while (!infile.eof()) { add_from(infile);` to `while (add_from(infile)) {` Also remember to return true at the last line of add_from() to indicate success. – drescherjm Mar 03 '22 at 14:12

0 Answers0