0

I am trying to make a program that reads from a student.txt file, and takes the information from that file and places it in a vector of students.

Student.txt:

1 James 23
0 HaHa 7012
1 Jay-Z music

I overloaded the >> operator:

std::istream& operator>> (std::istream& input, Student& student)
{
    char id;
    std::string user, pswd;
    input >> id >> user >> pswd;

    if (id == '0')
    {
        student.setUsername(user);
        student.setPassword(pswd);
    }
    return input;
}

For the student class, then I made a function that takes the file and vector as parameters, and populates the vector with student objects.

void getStudents(std::fstream& file, std::vector< Student >& list)
{
    char userType;
    std::string user, pswd;
    file.seekg(0, file.beg);

    Student newStudent;
    while (!file.eof())
    {
        file >> newStudent;
        list.push_back(newStudent);
    }
}

I also overloaded the >> operator to print the student class to cout:

std::ostream& operator<< (std::ostream& output, Student& student)
{
    output << "Username: " << student.getUsername() << std::endl << "Password: ";
    output << student.getPassword() << std::endl;
    return output;
}

Finally, I wrote this in main() to test if it is all working:

vector<Student> students;
fstream studentFile("Student.txt", ios::in);

cout << "Students:\n\n";
getStudents(studentFile, students);

for (int i = 0; i < (int)students.size(); i++)
{
    cout << students[i];
}   

But, when I run it, it outputs:

Students:

Username:
Password:
Username: HaHa
Password: 7012
Username: HaHa
Password: 7012
Teachers:

I'm not really sure how to fix it. Everything worked fine when I read from cin instead of the student.txt file.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
corl
  • 1
  • 1
  • 3
    [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Oct 30 '22 at 18:46
  • 1
    ^ That's part of the issue, the other would be that your operator can produce an invalid (?) `Student`, but you never check if that happened when reading file, before pushing such invalid Student into the vector. – Yksisarvinen Oct 30 '22 at 18:49
  • i changed it so that it checks if it is a valid student object which fixed the empty fields, but it is still creating duplicate students in the vector. – corl Oct 30 '22 at 19:27
  • @corl Fixing the broken `while` loop should avoid the issue with invalid students in the vector. Change `while (!file.eof()) { file >> newStudent; list.push_back(newStudent); }` to `while (file >> newStudent) { list.push_back(newStudent); }` – Remy Lebeau Oct 30 '22 at 19:48

0 Answers0