I'm working my way through Accelerated C++ and I've come across this exercise. The read_hw function works fine if it's void as long as I comment out the "return in" line. The author didn't bother to explain why he's returning a reference to the cin that was passed in the first place. Also I'm not sure what to make of the if (in) here, since it was passed as a parameter it seems like it should be there. I would greatly appreciate any (correct) explanation for almost anything going on here related to istream/cin.
// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw)
{
if (in)
{
// get rid of previous contents
hw.clear();
// read homework grade
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}
int main()
{
vector<double> homework;
read_hw(cin, homework);
return 0;
}