C++20 sections · 1024 units
Open in Course

Word Counter - The Idea

File reading pattern

When you write while (infile >> word), the stream extracts one word at a time, skipping whitespace automatically. The expression returns false when no more data can be read, ending the loop.

Opening a file requires creating an ifstream object with the filename. Always check if the file opened with if (!infile) or if (infile.fail()).

For counting words, initialize a counter to zero and increment it each time you successfully extract a word. After the loop, the counter holds the total. This read-and-count pattern applies to many file processing tasks.