Problem with a function that reads a stream until eof.

Write a function that takes and returns an istream&. The function should read the stream until it hits the end of file.
The function should print what it read to the standard output.Reset the stream so it is valid before returning the stream

1
2
3
4
5
std::istream& read(std::istream& i){
    while(!i.eof()){
        ...
    }
}

That function is not finished yet ;)
Why do we need to return a reference to an istream object? I cannot do std::cout << std::cin.
In the ..., I store the string using getline and pushback that into a vector.
And then iterate through the vector and print all the strings in it.

My real problem is why I should return a istream&.
This question was on the C++ Primer book.
> Why do we need to return a reference to an istream object? I cannot do std::cout << std::cin.
Yes, you can.
You can also do std::cin >> foo >> bar; There the std::cin>>foo return an istream so `'bar' can also be read.

Another reason is to be able to check if the operation was successful (by instance, your function may file if the file does not exist)
1
2
while( std::cin >> word )
while( std::getline(std::cin, line) )
(those methods are preferred instead of looping on eof)

You can also do std::cin >> foo >> bar; There the std::cin>>foo return an istream so `'bar' can also be read.

Yes, but why do we need it in my function?

I can as easily rewrite this function in another way:
1
2
3
4
5
6

void read( std::istream& i, std::string s){
    while(std::getline(i,s)){
        std::cout << s << "\n";
    }
}

It will also read from an istream and print out that on console.
Topic archived. No new replies allowed.