Thursday, 13 July 2017

c++ - eof() bad practice?











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?


Answer



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";
}
}

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...