It's explained elsewhere on this site already.
In this order:
in.eof()
checks eofbit
which is false. No read operation has read the end of file yet. The loop continues.
in >> str
encounters the end of file and sets eofbit
. This also leaves str
unchanged from the last iteration,
- you push the old (unchanged)
str
which is now in your vector twice,
- you exit the loop when
in.eof()
checks eofbit
.
Your misunderstanding is that in.eof
is doing something to detect the
end of file condition -- but, it's not. It just checks eofbit
.
eofbit
isn't set until the >>
operation is performed.
Carefully read documentation for ios::eof, which I shall excerpt here:
std::ios::eof
Returns true if the eofbit
error state flag is set for the stream.
This flag is set by all standard input operations when the End-of-File
is reached in the sequence associated with the stream.
Note that the value returned by this function depends on the last
operation performed on the stream (and not on the next).
To fix the problem
in >> str
will return whether or not a string was read. Just base your loop condition on that.
while(in >> str)
vec.push_back(str);