in main:
ifstream file("text.txt");
string line;
while (file) {
file>>line;
cout<<line<<endl;
}
in text.txt:
hello
goodbye
output:
hello
goodbye
goodbye
Why is the last line printed twice?
in main:
ifstream file("text.txt");
string line;
while (file) {
file>>line;
cout<<line<<endl;
}
in text.txt:
hello
goodbye
output:
hello
goodbye
goodbye
Why is the last line printed twice?
Duplication: When you read 'goodbye' for the first time, you don't know that you reached the end of file and go to the next iteration. Then fail to read, get eof
bit set, but print out the current value of line
, which remains to be 'goodbye'.