C++ Program to Count Number of Words in a Sentence

Here is a C++ program to count the number of words in a string. In this C++ program, we will count the number of words in a sentence. Words are separated by one or multiple space characters.

For Example :
Input Sentence: I love C++ programming
Word Count : 4

To find the number of words in a sentence, we will first take a string input from user and store it in a character array(string). Here we are using strtok function of header file to split a sentence into words.

strtok Function
  • The function char *strtok(char *str, const char *delimiters); breaks string str into tokens, which are sequences of contiguous characters separated by any of the characters of string delimiters.
  • First call to strtok function expects a C string as argument str, and returns first token. Subsequent calls of strtok function expects a null pointer argument and returns next word. strtok function is widely use to tokenize a string into words.

C++ Program to Count Words in Sentence

#include <iostream>
#include <cstring>
using namespace std;
 
int main() {
   char string[100], *token;
   int count = 0;
    
   cout << "Enter a string\n";
   cin.getline(string, 100);
    
   token = strtok(string, " ");
    
   while(NULL != token) 
   {
       count++;
       token = strtok(NULL, " ");
   }
    
   cout << "Word Count : "<<count;
   return 0;
}
Output
Enter a string
I love C++ programming
Word Count : 4

Recommended Posts
C++ Program to Delete a Word from Sentence
C++ Program to Convert Uppercase to Lowercase Characters
C++ Program to Print Array in Reverse Order
C++ Program to Delete Spaces from String or Sentence
C++ Program to Check whether a string is Palindrome or Not
C++ Program to Count Number of Vowels, Consonant, and Spaces in String
C++ Program to Find the Frequency of Characters in a String
C++ Program to Copy String Without Using strcpy
C++ Program to Convert Decimal Number to Binary Number
All C++ Programs