odbhut.shei.chhele
odbhut.shei.chhele

Reputation: 6264

I am confused about End of File

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.

Upvotes: 0

Views: 133

Answers (1)

Robᵩ
Robᵩ

Reputation: 168836

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

Upvotes: 6

Related Questions