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_iterator
object: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...