Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eof() bad practice? [duplicate]

Tags:

Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?

So I've been using the eof() function in a lot of my programs that require file input, and my professor said that it is fine to use but a few people on SO have said that I shouldn't use it without really specifying the reason. So I was wondering, is there a good reason?

like image 689
Sam Avatar asked Apr 29 '11 21:04

Sam


People also ask

Is EOF false?

The EOF macro doesn't signal anything, since it is just a value.

Is EOF false in C?

EOF will be false, and the loop will terminate.

Why is EOF not working C++?

eof()) loop doesn't work, because streams/files in C and C++ don't predict when you have reached the end of the file, but the rather indicate if you have tried to read past the end of the file.

What does EOF mean in pseudocode?

In computing, end-of-file (EOF) is a condition in a computer operating system where no more data can be read from a data source.


1 Answers

You can use eof to test for the exact condition it reports - whether you have attempted to read past end of file. You cannot use it to test whether there's more input to read, or whether reading succeeded, which are more common tests.

Wrong:

while (!cin.eof()) {   cin >> foo; } 

Correct:

if (!(cin >> foo)) {   if (cin.eof()) {     cout << "read failed due to EOF\n";   } else {     cout << "read failed due to something other than EOF\n";   } } 
like image 109
Erik Avatar answered Nov 09 '22 18:11

Erik