Hi, I am stuck on exercise 8.1 (at section 8.1.2) p314 of C++ Primer 5th Edition (Lippman, Lajoie, Moo). The exercise says: "Write a function that takes and returns an istream&. The function should read the stream until it hits end-of-file. The function should print what it reads to the standard output. Reset the stream so that it is valid before returning the stream." Suppose I have declared: istream& read(istream&); How do I go about defining this function? Thanks in advance.
Start by giving the name to the argument, opening the body of the function (a curly brace should do), and returning the argument passed in, then closing the body (another curly brace). Do you know how to read the stream? The simplest is reading one char at a time. Do you know how to check the stream's "end-of-file" condition? Do you know how to define a loop *until* some condition is met (hint: use 'while')? V
Is this a correct solution? #include <iostream> #include <string> istream& read(istream& in) { std::string word; while(in >> word) { std::cout << word; } // reset stream so it's in a valid state in.clear(); return in; }
If I try to compile this I get an error: #include <iostream> #include <string> // declaration istream& read(istream&); // definition istream& read(istream& in) { std::string word; while(in >> word) { std::cout << word << endl; } // reset stream so it's in a valid state in.clear(); return in; } int main() { std::cout << "Input some txt"; read(std::cin); return 0; } ------------------------