C++ File handling: Count number of words in a text file
4. Count the Number of Words in a Text File
Write a C++ program to count the number of words in a text file.
Sample Solution:
C Code:
Sample Output:
Number of words in the said file: 76
Explanation:
In the above exercise,
- Use the std::ifstream class to open the text file.
- Check if the file was successfully opened using the is_open() function.
- If the file is open, declare an int variable wordCount to keep track of the number of words.
- Then use a while loop and std::getline() to read each line from the file. Inside this loop, use std::stringstream to break the line into individual words.
- Use another while loop with ss >> word to extract each word and increment the wordCount for each word encountered.
- Display the total number of words on the console after the loops end using inputFile.close().
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to open a text file and count the words by reading each line and splitting by spaces.
- Write a C++ program that uses string streams to parse each line of a file and count the total number of words.
- Write a C++ program to read a file and count words by iterating through each character and detecting word boundaries.
- Write a C++ program to process a text file and output the number of words, ignoring punctuation and multiple spaces.
CPP Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Open and display text file contents.
Next C++ Exercise: Copy contents from one text file to another.
What is the difficulty level of this exercise?