1

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?

Michael Dorst
  • 8,210
  • 11
  • 44
  • 71
  • 2
    see: http://stackoverflow.com/questions/7868936/c-read-file-line-by-line – pb2q Oct 06 '12 at 04:27
  • @pb2q That's great, but that question isn't the same as the question I was asking. I know there are other (maybe better) ways to do what I want, but I want to know why _this_ way doesn't work, and why it does what it does. – Michael Dorst Oct 06 '12 at 04:33
  • I understand why "hello" is printed twice, but not why "goodbye is omitted. I can't reproduce your results. – Beta Oct 06 '12 at 04:44
  • Huh... Well thanks for trying. Can you tell me why hello is printed twice? Cause I don't understand that part. – Michael Dorst Oct 06 '12 at 04:46
  • when I compile it, I get: `hello goodbye goodbye` – Rontogiannis Aristofanis Oct 06 '12 at 05:59
  • possible duplicate of [Do I need to manually close a ifstream?](http://stackoverflow.com/questions/748014/do-i-need-to-manually-close-a-ifstream) – Wh1T3h4Ck5 Oct 06 '12 at 16:02

1 Answers1

2

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'.

Michael Dorst
  • 8,210
  • 11
  • 44
  • 71
Shamdor
  • 3,019
  • 5
  • 22
  • 25