[Cs3] using extraction operation in conditions
Mikhail Nesterenko
mikhail at cs.kent.edu
Sun Sep 27 13:21:36 EDT 2015
CS3 students,
There was a question on using the extraction operator in a conditional
expression like inside the while loop. For example:
int i;
while(filestream >> i)
// do something with i
Somehow, I was never comfortable doing that since to me it looks
unintuitive. The reason that it works is this: extraction operator
above is an alliterative form of
iostream& operator >> (iostream&, i)
This operator returns a stream so that it can be stacked. If used in
an expression, the compiler implicitly invokes a bool() operator on
this stream
http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
that returns true if there were no errors in reading from the stream
and false otherwise. One of the errors is end-of-file condition.
Now, using eof() to check for the end of file, such as
while(!filestream.eof()){
int i;
cin >> i;
// do something with i
}
although used in some places such as the textbook we use for CSI, is
discouraged since it only catches end-of-file condition and may skip
another file reading error.
I recoded the roster example we used in class.
thanks,
--
Mikhail
More information about the cs3
mailing list