Program to count word in a sentence in C++

Program to count word in a sentence

Input : Takes a string and count the number of words in the input string.

Example:

Input: Welcome to C++

Output: Total number of words in a sentence is 3

Algorithm

  1. Create a string variable and prompt the user to enter a sentence.
  2. Find the length of the string using the strlen() function.
  3. Initialize a counter variable to 0.
  4. Iterate over the string using a loop, starting from the first character and ending at the last character.
  5. Inside the loop, increment the counter variable if an empty space character (' ') is encountered.
  6. After the loop, print the number of words in the sentence as the counter variable plus 1 (since the number of words is 1 greater than the number of spaces).

Code:

// C++ Program To Count Word in a Sentence
#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

int main() {
    char str[100];
    int i, len, count = 0;
    
    cout << "Write a sentence: ";
    gets(str);
    
    len = strlen(str);
    
    for (i = 0; i < len; i++) {
        if (str[i] == ' ') {
            count++;
        }
    }
    
    cout << "Total number of words in a sentence is " << count + 1;
    
    return 0;
}

Output

Input:
Write a sentence: The quick brown fox jumps over the lazy dog.

Output:
Total number of words in a sentence is 9