In this section, we will write a one-liner function that counts the words from an input buffer, and let the user choose where the input buffer reads from:
- Let's include all the necessary headers first and declare that we use the std namespace:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
- Our wordcount function accepts an input stream, for example, cin. It creates an std::input_iterator iterator, which tokenizes the strings out of the stream and then feeds them to std::distance. The distance parameter accepts two iterators as arguments and tries to determine how many incrementing steps are needed in order to get from one iterator position to the other. For random access iterators, this is simple because they implement the mathematical difference operation (operator-). Such iterators can be subtracted from each other like pointers. An istream_iterator however, is a forward iterator and must be advanced until it equals the end iterator. Eventually, the number of steps needed is the number of words:
template <typename T>
size_t wordcount(T &is)
{
return distance(istream_iterator<string>{is}, {});
}
- In our main function, we let the user choose if the input stream will be std::cin or an input file:
int main(int argc, char **argv)
{
size_t wc;
- If the user launches the program in the shell together with a file name (such as $ ./count_all_words some_textfile.txt), then we obtain that filename from the argv command-line parameter array and open it, in order to feed the new input file stream into wordcount:
if (argc == 2) {
ifstream ifs {argv[1]};
wc = wordcount(ifs);
- If the user launched the program without any parameter, we assume that the input comes from standard input:
} else {
wc = wordcount(cin);
}
- That's already it, so we just print the number of words we saved in the variable wc:
cout << "There are " << wc << " wordsn";
};
- Let's compile and run the program. First, we feed the program from standard input without any file parameter. We can either pipe an echo call with some words into it or launch the program and enter some words from the keyboard. In the latter case, we can stop the input by pressing Ctrl+D. This is how echoing some words into the program looks:
$ echo "foo bar baz" | ./count_all_words
There are 3 words
- When launching the program with its source code file as input, it will count how many words it consists of:
$ ./count_all_words count_all_words.cpp
There are 61 words