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.