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;
}
You're not using the return value, so it doesn't really matter what the function returns. However, there are times when it's convenient for a function that works with streams to return the stream, so it can be used by another function.
#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>
usingnamespace std;
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()
{
double a, b;
vector<double> homework;
cin >> a >> b >> read_hw(cin, homework);
system("pause"); //bad form, i know
return 0;
}
and the error i get is:
ambiguous load for 'operator>>' etc.
thoughts? i'm clearly failing to grasp something very basic here.