0

I am really confused about End of File. Suppose I am running an infinite loop. And in this loop I am taking an integer as input and then processing it, until I find an End of File. But do I check whether the input is an End of File or not. And how do I break the loop?

I use Windows, so for EOF I am typing CTRL+Z.

#include<iostream>
#include<cstdio>
using namespace std;

int main(void)
{
  int n;
  while(true)
  {
    cin >> n;
    if(n==EOF)break;
    cout << n << endl;
  }
  return 0;
}

When I run this code and I type CTRL+z, it prints only the last input I have given, endlessly.

halfer
  • 19,824
  • 17
  • 99
  • 186
odbhut.shei.chhele
  • 5,834
  • 16
  • 69
  • 109

1 Answers1

6

1) That isn't how you check for end-of-file. Where did you read that operator>> would return an EOF value?

The correct way to see if you have tried to read past end-of-file is this if(cin.eof()). But, don't ever do that, because:

2) You shouldn't ever check for end-of-file. Rather, you should check for "did that last input operation work correctly?"

Like this:

#include<iostream>
#include<cstdio>
using namespace std;

int main(void)
{
  int n;
  while(cin >> n)
  {
    cout << n << endl;
  }
  return 0;
}


Reference: Reading from text file until EOF repeats last line
Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 2
    Don't forget to upvote any answer that helped you, and accept a single answer that solved your problem. – Robᵩ Jul 12 '12 at 20:35
  • This will break as soon as reading an integer fails, though, which may be before the end of the available input. – Kerrek SB Jul 12 '12 at 20:43
  • @KerrekSB, True, but I'd say that's a whole new question (with a lot of dupes). The original code didn't have any form of verification either. – chris Jul 12 '12 at 20:57