0

Hi,

i wish to know the difference between the following two code?

ifstream fin(fname,ios::in);
vector<string> temp;

while(getline(fin, line)
{
       temp.push_back(line);
}

and

while(!fin.eof())
{
       getline(fin,line);
       temp.push_back(line);
}

thanks

Edited by Reverend Jim: Fixed formatting

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by ArkM
0

Feel the difference: the 1st loop is correct, the 2nd one is wrong.
A stream eof state detected only after some input operation. Suppose the file contains a single line:
1. eof() returns false.
2. getline gets a line (no eof state detected now)
3. push a line, OK
3. eof() return false!
4. getline DOES NOT get a line, set eof flag
5. push... what?.. a previous line contents!
6. eof() returns true, break the loop...
We have TWO lines in the vector ;(

So it was the question about eof() incorrect usage, not getline...

Apropos, ifstream => ios::in, of course ;)

Yet another tip: stop senseless code tag usage. That's right:
dear all...bla bla bla...urgent...my compiler does not work...
[code=cplusplus] source

[/code]
bla bla bla...thank you

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.