I'm trying to get a better understanding of ifstream, and was playing with it using the program below. It's purpose was to grab the first and last entries in the file, instead I get some perplexing output leading me to realize I've very little clue as to how streams really work. I know the simple book nuts and bolts, but putting it into practice is different. (and yes I am avoiding .eof() on purpose)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream names;
names.open("P25.txt");
string firstInFile;
string lastInFile;
string next;
string students;
while(names >> students)
{
names >> firstInFile;
names >> lastInFile;
}
names.close();
cout << firstInFile << endl;
cout << lastInFile << endl;
return 0;
}
/*
P25.txt
-------
Amy
Angela
Vicky
KC
Stephanie
Mark
Andrea
Tom
*/
What I'm getting in output is:
Tom
Mark
If I change the code a little like this:
names >> firstInFile;
while(names >> students)
{
names >> lastInFile;
}
The output is :
Amy
Andrea
I get Amy, as it's the first entry in the file, but why does it stop at Andrea, when there is one more entry it can read in.
Also,
If I just have this:
while(names >> students)
{
names >> lastInFile;
}
With no other reading, it does indeed return the last entry in the file.
I know this is a pretty simple question, but I'm really trying to get a decent grasp on what's going on.