Search code examples
c++iteratoristream

C++ Iterate an istream


What is the best way to parse or iterate an istream? I need to create a function that takes an istream, parses it and creates an object so was wondering the easiest way to do this. Even something that could convert it to string would be dandy.


Solution

  • You can use an istream_iterator.

    typedef std::istream_iterator<std::string> streamiter;
    for (streamiter it = streamiter(some_istream); it != streamiter(); it++) {
        // process words
    }
    

    This will split the input stream at all whitespaces.