Count Words in a Text File Using C++

In this exercise, you will write a C++ program that reads a text file and counts the total number of words contained in it. This task will help you become familiar with file input operations using the `ifstream` class and manipulating strings with the `stringstream` class. You will learn how to process a file line by line and tokenize each line to count words individually. This exercise is useful for building tools such as basic text analyzers or utilities that process textual data.

Group

File Management in C++

Objective

1. Open an existing text file for reading using `ifstream`.
2. Read the file line by line.
3. For each line, use a `stringstream` to extract words.
4. Count the total number of words.
5. Display the total count on the screen.

Implement a program that counts the words in a text file.

Example C++ Exercise

 Copy C++ Code
#include <iostream>       // Include for standard input and output
#include <fstream>        // Include for file input stream
#include <sstream>        // Include for stringstream
#include <string>         // Include for using the string class

using namespace std;

int main() {
    ifstream file("sample.txt");      // Open the file 'sample.txt' for reading
    string line;                      // Variable to hold each line from the file
    int wordCount = 0;                // Counter to track total number of words

    // Check if the file was opened successfully
    if (file.is_open()) {
        // Read the file line by line
        while (getline(file, line)) {
            stringstream ss(line);    // Create a stringstream for the current line
            string word;              // Variable to store individual words

            // Extract words from the line
            while (ss >> word) {
                wordCount++;          // Increment the word counter for each word
            }
        }

        file.close();  // Close the file after reading

        // Output the total number of words
        cout << "Total number of words in the file: " << wordCount << endl;
    } else {
        // Display error message if file couldn't be opened
        cout << "Error: Could not open file." << endl;
    }

    return 0;  // End of program
}

 Output

//Output Example:
Total number of words in the file: 42

//Content of sample.txt (for reference):
This is a sample text file.
It contains several lines of words.
The program should count them all correctly.

Share this C++ Exercise


More C++ Programming Exercises of File Management in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.

  • Copy File Contents Using C++

    This exercise involves writing a C++ program to copy the entire content of one file into another. By completing this task, you will practice using file streams in C++, specifically...

  • Find and Replace a Word in a File Using C++

    In this exercise, you will create a C++ program that searches for a specific word in a text file and replaces it with another word. This task will help you strengthen your understa...

  • Save and Load a List of Numbers from a File in C++

    In this exercise, you will create a C++ program that allows the user to input a list of numbers, save them to a text file, and then read and display those numbers from the file. Th...

  • Count the Number of Lines in a Text File Using C++

    This exercise guides you through the process of writing a C++ program that reads a text file and counts the number of lines it contains. This is a fundamental operation when analyz...

  • Sort the Lines of a Text File Using C++

    This exercise involves creating a C++ program that reads all lines from a text file, sorts them in alphabetical order, and then displays the sorted lines on the screen. Sorting fil...

  • Delete a Specific File Using C++

    In this exercise, you will write a C++ program that deletes a specific file from the system using file handling operations. Managing files programmatically is an essential skill in...