function to read a stream

Discussion in 'C++' started by nvangogh, May 13, 2014.

  1. nvangogh

    nvangogh Guest

    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.
     
    nvangogh, May 13, 2014
    #1
    1. Advertisements

  2. 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
     
    Victor Bazarov, May 13, 2014
    #2
    1. Advertisements

  3. nvangogh

    nvangogh Guest

    could you show the code?
     
    nvangogh, May 13, 2014
    #3
  4. nvangogh

    nvangogh Guest

    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;
    }
     
    nvangogh, May 13, 2014
    #4
  5. nvangogh

    nvangogh Guest

    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;
    }

    ------------------------
     
    nvangogh, May 13, 2014
    #5
  6. nvangogh

    nvangogh Guest

    Its ok I've done it
     
    nvangogh, May 13, 2014
    #6
  7. nvangogh

    nvangogh Guest

    I know its a simple exercise, which I have solved now.
     
    nvangogh, May 13, 2014
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.