Menu

TIP/Trick: How to count words in a text file using C++

Sometimes we may find ourselves handling data files that contain information whose data integrity needs to be checked or compared against rules related to byte size, amount of lines or amount of WORDS. Hence the need of having a function to count the amount of words in a string in our string extensions library.

Working with files in middle level languages like C & C++ can be an obscure task for people who are getting started with programming. High level languages like C#, Java or Ruby do a pretty good job creating an intuitive abstraction layer to avoid overwhelming the programmer with the raw compelling nuances when handling files.

Loading the file

I’ve implemented the countWords function for both, null terminated char sequences and strings, as well as the read file function for each case. Heres the code:

Counting the Words

Disclaimer: This is a very simple implementation and some edge cases have been obviated. This is just an attempt of pointing in the right direction people that struggle when trying to approach this task.