Why does accelerated cpp have me return istream& here when void works?

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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.

For example:
 
std::istream& operator>>(std::istream&, int&);


allows you to write code like:
1
2
int a, b, c;
std::cin >> a >> b >> c;
disclaimer: this is going to be really noobish.
so based on this thread in conjunction with another i'm crossposting in, i put together this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>

using namespace 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.
Last edited on
Topic archived. No new replies allowed.