i need help

hi i am studying the Addison Wesley 's Accelerated c++ ,however i cant understand the part number 4.1.3 which says:

1
2
3
4
5
6
7
8
9
10
// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw) {
    // we must fill in this part
	
    return in;
}

vector<double> homework; 

read_hw(cin, homework);


i think every parameter we will pass in this function will be a ref to in or hw

but what does istream& means and why did we use this function and what does it do. i am a big newbie so help me please.

thanks.



Is this an exact copy of what you are given? It doesn't do anything with cin (I'm guessing it might be a dummy variable). Run:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <istream>  // for istream
#include <iostream> // for cin and cout
#include <vector>   // for vector

std::istream& read_hw(std::istream&, std::vector<double>&); // Predeclaration


int main(int argc, char** argv[])
{
    std::vector<double> homework; 
    read_hw(std::cin, homework);

    return 0;
} 

// read homework grades from an input stream into a vector<double>
std::istream& read_hw(std::istream& in, std::vector<double>& hw) 
{
    // we must fill in this part

    return in;
}


and you will see. It does not request a cin input.

istream is an STL function used for inputting data. When reading from a file, you will typically see ifstream (In File Stream), which inherits from istream.

It appears you aren't trying to accomplish anything with returning istream ( the istream& declaration before read_hw ). If that is the case, you should replace it with void. i.e.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <istream>  // for istream
#include <iostream> // for cin and cout
#include <vector>   // for vector

void read_hw(std::istream&, std::vector<double>&); // Predeclaration


int main(int argc, char** argv[])
{
    std::vector<double> homework; 
    read_hw(std::cin, homework);

    return 0;
} 

// read homework grades from an input stream into a vector<double>
void read_hw(std::istream& in, std::vector<double>& hw) 
{
    // we must fill in this part

}


The & at the end is passing the reference (location of the variable) so you modify istream directly. If you don't pass the reference, you will pass a copy of istream and later functions accessing istream will get passed the original version of istream and be ignorant of anything modified by the previous function

// we must fill in this part
Looks like that is what they need to do, implement that function using the istream. I suggest looking at the read this http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/ and take a look at the examples and try it out.
Last edited on
@clanmjc

Omg. 110 posts already!?

O.O Unbelievable(Lol).
Last edited on
Topic archived. No new replies allowed.