STL - What is an istream_iterator?

Tuesday, September 1, 2009

Class: istream_iterator

Iterators constructed by istream_iterator are input iterators, but they are not output iterators. Means that istream_iterator objects can read data only in a single direction, and data cannot be written through an istream iterator object.

Constructors:
The class istream_iterator provides two public constructors.

1) istream_iterator(istream &) This constructor provided by the istream_iterator type produces an input iterator for values of type T from a given input stream.

2) istream_iterator() This constructor provided by the istream_iterator produces an input iterator that works as an end marker for istream iterators. This is simply a value to which istream iterators become equal when the istream they are scanning reports an end of stream condition.

Lets see an example where we use the istream_iterator to read strings from an input file and load the strings in a vector.

Note: The following code is just a code snippet, not the full program.

...
cout << "Enter the dictionary file name:";
string dictionaryName;
cin >> dictionaryName;

ifstream dfs(dictionaryName.c_str());
if(!dfs.is_open())
{
cout << "Unable to open the given dictionary file name.";
return 1;
}
cout << "Reading the dictionary file...\n";
typedef istream_iterator<string> string_stream;

vector<string> words;

copy(string_stream(dfs),string_stream(), back_inserter(words));
...

The above program takes the name of an input file which contains list of words. If the file is available and opens properly, it reads the words from the input file and creates a vector of strings.

We create an istream iterator for type string and then create an instance of the istream iterator to read the data from the input file stream.

Please try this out. Of course, we have not explained about the copy(...) STL function available in the header file algorithm and also the back_inserter(...). We'll see about them in tomorrow's post.

0 comments: to “ STL - What is an istream_iterator? so far...