C++ Program to Count Words in Text

 

 

Word Count Program in C++

This document provides a C++ program to count the number of words in a given text. The program structure and the code documentation are explained in detail.

Program Explanation

The program reads input text from the user and counts the number of words in the text. A word is defined as any sequence of characters separated by whitespace.

Program Structure

  • Include necessary headers: We include the necessary headers for input-output operations and string handling.
  • Main function: The entry point of the program where we read the input text and count the words.
  • Word counting logic: We use a string stream to break the input text into words and count them.

C++ Program Code


// Include necessary headers
#include <iostream>
#include <sstream>
#include <string>

// Main function
int main() {
    // Variable to store the input text
    std::string text;

    // Prompt the user for input
    std::cout << "Enter the text: ";
    std::getline(std::cin, text);

    // Create a string stream from the input text
    std::stringstream ss(text);

    // Variable to store each word
    std::string word;
    // Counter for words
    int wordCount = 0;

    // Extract words from the string stream
    while (ss >> word) {
        wordCount++;
    }

    // Display the word count
    std::cout << "Number of words: " << wordCount << std::endl;

    return 0;
}
    

Documentation

The following is a detailed explanation of the code:

  • #include <iostream>: Includes the header file for input-output stream operations.
  • #include <sstream>: Includes the header file for string stream operations.
  • #include <string>: Includes the header file for string handling.
  • int main(): Defines the main function where the program execution begins.
  • std::string text;: Declares a string variable to store the input text.
  • std::cout << "Enter the text: ";: Prompts the user to enter the text.
  • std::getline(std::cin, text);: Reads the entire line of input from the user and stores it in the text variable.
  • std::stringstream ss(text);: Creates a string stream object ss initialized with the input text.
  • std::string word;: Declares a string variable to store each extracted word.
  • int wordCount = 0;: Initializes a counter variable to count the words.
  • while (ss >> word): Extracts words from the string stream ss one by one and increments the word count.
  • std::cout << "Number of words: " << wordCount << std::endl;: Displays the total number of words counted.
  • return 0;: Indicates that the program ended successfully.

Usage

To use this program, compile it with a C++ compiler and run the executable. Enter the text when prompted, and the program will output the number of words in the entered text.

 

Leave a Reply

Your email address will not be published. Required fields are marked *