istream_iterator<T>

An istream_iterator is an iterator adapter that reads data from an input stream. Using the ++ operator normally used to advance an iterator instead uses the stream extraction operator << to read from a stream. This allows you to use STL algorithms on ifstreams, or to populate the contents of a container from the console.

istream_iterator is a class template whose template argument indicates the type of element to read from the stream. For example, an istream_iterator<int> will read ints from a stream, while an istream_iterator<string> reads strings. Remember that because the istream_iterator uses the << operator to read from a stream, istream_iterators will use whitespace as delimeters.

As with other input iterator classes, you will need two istream_iterators to delineate a range. While you can construct an istream_iterator for any input stream, the STL only defines a single istream_iterator suitable for use as an end iterator. An istream_iterator constructed using the default constructor (which has no parameters) creates an istream_iterator indicating "end of stream." Reading values from such an istream_iterator results in undefined behavior, so be sure to avoid doing so.

istream_iterator<T> Member Functions
istream_iterator<T>(istream &input)
Constructs an istream_iterator that reads from the specified stream.
istream_iterator<int> itr(cin); // An iterator that reads from cin.

Constructs a new istream_iterator that reads from the specified stream. When the iterator encounters an end of file or the stream enters a fail state, the iterator will take on the sentinel value istream_iterator<T>().

istream_iterator<T>()
Constructs a special istream_iterator indicating end-of-stream.
istream_iterator<int> itr(); // An end-of-stream indicator.
accumulate(istream_iterator<int>(myStream), istream_iterator<int>(), 0); // Add the value of all ints in the stream myStream.

Constructs a new istream_iterator that acts as an "end-of-stream" iterator. Use this iterator when defining iterator ranges with an istream_iterator.