I am currently trying to write a program that sorts a vector based on columns. I am think i am all done, however i am currently adding the contents of the vector in the actual code as you can see on lines 31-33. What i want to do is to have the content in textfile input.txt. The reason is because the assignment i have has that as a rule.
So how do i add a text file into a vector so it has the same function as i already do in my code on lines 31-33.
No. Don't loop on eof(). It is an error-prone approach, for more than one reason.
You need to check the status of the file after reading it, not before.
Replace this:
1 2 3 4 5 6 7 8
while (!reader.eof())
{
Data data;
reader >> data.i;
reader >> data.s1;
reader >> data.s2;
container.push_back(data); // no idea whether the read succeeded, but process it anyway
}
with this:
1 2 3 4 5
Data data;
while (reader >> data.i >> data.s1 >> data.s2)
{
container.push_back(data); // process only after the read was successful
}
Here the body of the loop (the push_back) is executed only after a successful read from the file.