I'm having some trouble with creating a file system to my program in C++. Well, I am creating a new student, and, if he is the last object that I'm creating before saving the files and closing the program, it gets duplicated. For example, two objects: Daniel, Paul. It shows just the last one duplicated: Daniel, Paul, Paul - in the file.txt.
Here is some code of mine:
FILE READING:
ifstream file;
file.open("file.txt");
while (1)
{
Student *p = new Student();
if (file.eof() || file.bad() || file.fail())
{
break;
}
getline(file, ALLTHESTRINGVARIABLES);
p->STRINGVARIABLES = ALLTHESTRINGVARIABLES;
file >> ANOTHERVARIABLES;
p->NOTSTRINGVARIABLES = ANOTHERVARIABLES;
students.push_back(p);
}
file.close();
FILE WRITING:
fstream file;
file.open("file.txt", ios::out | ios::trunc);
for(unsigned int i = 0; i < students.size(); i++){
file << students[i]->VARIABLEEXAMPLE << endl;
}
file.close();
Thank you!!
The eof(), bad(), fail() will only return true after a try to read some bytes from the file without success. So, put the if verification after the getline().
And just make the new instance of the Student after this if to avoid a memory leak.
Like that:
while (1)
{
getline(file, ALLTHESTRINGVARIABLES);
if (file.eof() || file.bad() || file.fail())
break;
Student *p = new Student();
p->STRINGVARIABLES = ALLTHESTRINGVARIABLES;
file >> ANOTHERVARIABLES;
p->NOTSTRINGVARIABLES = ANOTHERVARIABLES;
students.push_back(p);
}