So I have this code where an object of class Group has vector with objects from class Student. I am already writing information about the students from the vector into a file but I have problem with reading this information back. How can I do that?
Here is my code so far:
class Group { private: string name; vector <Student*> studentList; public: ~Group(); Group(void); Group(string s); void addStudent(string name,int age,int stNum); void removeStudent(int stNum); friend ostream& operator << (std::ostream& out, const Group& g) { out << g.name << "\n"; out << g.studentList.size() << "\n"; for (unsigned i=0;i<g.studentList.size();i++) { out<< g.studentList[i]->getStudentName()<<"\n"; out<< g.studentList[i]->getStudentAge()<<"\n"; out<< g.studentList[i]->getStudentNumber()<<"\n"<<endl; } return out; } friend istream& operator>>(std::istream& in, Group& g){ in >> g.name; for (unsigned i=0;i<g.studentList.size();i++) { //READ DATA FROM FILE } return in; } };
std::getlineto do the reverse.std::vectoris at it's absolute best when it contains things directly rather than pointing to them. There is far less memory management involved and since the data is stored contiguously in thevector, there can be orders of magnitude performance improvements.in >> *g.studentList[i], but first you would likely have tonewaStudentfor the pointer to point at. You probably don't want to have to put up with crap like that, though. See above comment. I would ditch pointers entirely andStudent temp; while (in >> temp) g.studentList.push_back(temp);