Reputation: 2183
Currently I am reading "Accelerated C++" and in an example in chapter 4, a function is written as to read from the input stream, which is as follows:
istream &read ( istream & in , vector < double >& work )
{
if ( in ) { // why it is needed ?
double x ; // x denotes the grade
work.clear ( ); // why we need it ?
while ( in >> x )
work.push_back ( x );
in.clear ( ); // understandable.
}
return in;
}
int main ( )
{
vector < double > homework;
vector <double> schoolwork;
read ( cin , homework );
read ( cin , schoolwork );
// code for output
}
Why is this needed:
if ( in ){.....}
Because while ( in >> x )
also plays that same role because when there is error (type mismatch, for example) in input stream then it will stop taking input and stream remains in error state, which is further cleared using in.clear()
. So that it can work for vector schoolwork
after homework
.
So why if ( in )
is needed although we have while ( in >> x )
which can perform the same?
Secondly, I am very much confused with work.clear( )
.
Why we need to clear the vector itself, although we are passing it with reference?
Upvotes: 1
Views: 67
Reputation: 254431
To leave the vector unchanged, rather than clearing it, if the stream is bad.
The behaviour of the function is to replace the contents of work
with the input. Without the clear
, it would append the input. The vague function name, and lack of documentation, make it unclear which is intended unless you read the code - renaming the function (e.g. replace
), or returning a vector by value rather than making the caller create one, would help with this ambiguity.
Upvotes: 3