Skip to main content
gamedev.net
🔒 Locked

istream_iterator

Started by wforl Jul 17, 2008 at 6:04 AM 2 replies 650+ views
Original Post
wforl
wforl
im a bit confused with the following code form Josuttis STL book. from what i understand it works as so... 1. Create an istream iterator, read info from console, and set intreader to beginning of input buffer. 2. create an end of file iterator, (default istream/ostream iterator) 3. While we havent reached the end of the text just read in, output the text, and iterating over each int. 4. When reached end of text end app. Yet the loop goes over again, and reads input again, but i cant seem to see where data is being read again, the while loop just checks for end of file.
#include <iostream>
#include <iterator>
using namespace std;

int main()
{
    // create istream iterator that reads integers from cin
    istream_iterator<int> intReader(cin);

    // create end-of-stream iterator
    istream_iterator<int> intReaderEOF;

    /* while able to read tokens with istream iterator
     * - write them twice
     */
    while (intReader != intReaderEOF) {
        cout << "once:       " << *intReader << endl;
        cout << "once again: " << *intReader << endl;
        ++intReader;
    }
}
ToohrVyk
ToohrVyk
++iter attempts to access the next element in the stream. It becomes equal to the EOF iterator if reading fails, and can otherwise be dereferenced to return the next element.
wforl
wforl
but shouldn't that drop put of the while loop then?
visitor
visitor
But it does. istream_iterator's (non-default) constructor reads first input, operator++ reads the next inputs. If any of the reads fails (you enter something that isn't an integer, or Ctrl+Z) the iterator is set to compare equal to the default-constructed end iterator, != returns false and the loop is exited.

Your book probably explains it, but normally you wouldn't use the iterator this way. You'd rather use it with algorithms that take iterators and not care about how exactly the istream_iterator works. For example, fill up a vector with integers as long as there's input:

vector<int> v;copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(v));

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.