Count words in a file
By default, the basic_istream class reads one word at a time. We can take advantage of this property to use an istream_iterator to count words.
How to do it…
This is a simple recipe to count words using an istream_iterator:
- We'll start with a simple function to count words using an
istream_iteratorobject:size_t wordcount(auto& is) { Â Â Â Â using it_t = istream_iterator<string>; Â Â Â Â return distance(it_t{is}, it_t{}); }
The distance() function takes two iterators and returns the number of steps between them. The using statement creates an alias it_t for the istream_iterator class with a string specialization. We then call distance() with an iterator, initialized with the input stream it_t{is}, and another with the default constructor, which gives us an end-of-stream sentinel.
- We call
wordcount()frommain():int main() { Â Â Â Â const char * fn{ "the-raven...