Advertisement Jump to content
Sign in to follow this  


This topic is 3841 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;

Share this post

Link to post
Share on other sites
++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.

Share this post

Link to post
Share on other sites
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));

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!