Syntactically correct, yes. But not logically. You're using
eof()
incorrectly.
The first thing to realize is that all of the functions which
test status base their results on the last input. And you must
always check that the input succeeded before using anything
you've input; when you write:
inFile >> grades;
std::cout << grades;
you are not verifying that the input succeeded before
accessing grades. In this case, if the input fails, you get the
previous value; if there were no previous value, you get
undefined behavior. Somewhere between the >>
and the <<
,
you must check that the >>
succeeded.
The usual way of checking for success is to use the stream
itself as a boolean. And because the >>
returns a reference
to the stream, the idiomatic way of writing your loop would be:
while ( inFile >> grades ) {
std::cout << grades << std::endl;
}
From a software engineering point of view, it's horrible
(modifying state in the condition of a while
), but the idiom
is so ubiquitous that anything else raises questions.
This will stop if there is an input error for any reason. Once
you've seen the failure (and only then), you can ask why:
if ( inFile.bad() ) {
// Serious hardware failure...
} else if ( !inFile.eof() ) {
// Format error in the input...
} else {
// Normally, no more data in the input stream, but
// there are a few special cases where you could still
// have a format error and end up here. Not with
// `int`, however.
}
But again, this is only valid after an input has failed.