C++ Program to Count the Number of Words in a String

In this article, you will learn and get code to count the total number of words present or available in a given string by the user at run-time in the C++ language.

For example, if you enter "codes cracker dot com," the total number of words is four.

In C++, count the total number of words in the string

To count the total number of words available in a string in C++ programming, you have to ask the user to enter the string or sentence first. And then count and print the result as shown in the program given below.

The question is, "Write a program in C++ that counts the total number of words in a string." Here is its answer.

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char str[200];
    int i=0, chk=0, countWord=0;
    cout<<"Enter the String: ";
    gets(str);
    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            if(chk!=0)
                countWord++;
            chk=0;
        }
        else
        {
            chk++;
        }
        i++;
    }
    if(chk!=0)
        countWord++;
    cout<<"\nTotal Number of Words = "<<countWord;
    cout<<endl;
    return 0;
}

This program was built and runs under the Code::Blocks IDE. Here is its sample run:

C++ program count number words sentence

Now supply any string, say, this is codes cracker dot com as input, and press the ENTER key to count and print the total number of words available in the entered string:

c++ count words in string

And here is another sample run with the following user input:

  this    is codes cracker    dot com  

That is, __this____is_codes_cracker____dot_com__. In this string, there are 2, 4, 1, 1, 4, and 1 spaces available before each word, and 2 spaces after the last word:

count words in string c++

The dry run of the above program with user input, this is codes cracker dot com, goes like this:

C++ Quiz


« Previous Program Next Program »