Creating a Word Counter in C++

Counting the amount of words in a string is one of the most basic programs that you can make in C++, taking only a few lines to complete. Due to its simplicity the word counter is a great way for beginners to further their understanding of how loops operate.

Libraries to Include

You need to include both the iostream and the string libraries for the program to be able to function properly.

#include<iostream>
#include<string>

Variable Definitions and User Input

After including the appropriate libraries begin the int main() function and define the string variable which will hold the user’s text.

int main()
{
     std::string str;

Next create a simple prompt for the user to enter in a string and grab it using std::getline. You need to use std::getline instead of std::cin for the purpose of getting user input otherwise the word counter will always return 1. This is because std::cin always stops at the first white space it encounters while std::getline won’t stop until it reaches the end of the inputted line regardless of whitespace.

std::cout << "Enter a string: ";
std::getline(std::cin, str);

The Word Count

Next you should define an int variable for the number of words that are counted.

int words = 0; // Holds number of words

Create a for loop that iterates through each character of the users string and checks for spaces. The loop must iterate up one every time it encounters a character that is not a space.

for(int i = 0; str[i] != '\0'; i++)
{
     if (str[i] == ' ') //Checking for spaces
     {
          words++;
     }
}

Lastly the user needs to see the result displayed to the screen. Make sure you do words plus one and not just words otherwise the final value displayed will be one less than it’s supposed to be.

std::cout << "The number of words = " << words+1;

Further Suggestions

For some additional challenge you can also have the program count the number of consonants and vowels as well as the number of occurrences of certain words. You can also try creating another version of the program which counts the number of words in a user selected text file. Here’s a basic version of that program to help get you started.

Good Luck!

Download the source code here

If you have any comments or questions email me at nick@crumbsofcode.com