Reputation: 6264
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
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;
}
Upvotes: 6