Count total number of words in a text file in C++

In this article, we will discuss with a program, how we can count the total number of words in a text file in C++ language. You can use a text file of any name, just make sure that the file already exists and has some content inside it.

Keep this text file in the same directory as the source code file.

For example, the file contains the text contains given below:

Hi,

Welcome to Codespeedy

The number of words here are: 4

Given below is the code implementation:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
 ifstream fin("fname.txt"); //opening text file
 int word=1; //will not count first word so initial value is 1
 char ch;

 fin.seekg(0,ios::beg); //bring position of file pointer to begining of file
 
 while(fin)
 {
  fin.get(ch);
  if(ch==' '||ch=='\n')
   word++;
 } 
 
 cout<<"\nWords="<<word<<"\n";
 fin.close(); //closing file
 
 return 0;
}

Example Output:

Words=3

 

Summarizing the article, the file handling implemented here is based on fstream library which contains the ifstream keyword. Also, always remember to close a file after reading or writing content using it. Another keyword used here was seekg, this keyword is used to change the location of the file pointer, which can be set at the beginning, ending or also at the current location of the file.

I hope, you have understood how our program works to count the total number of words that exist in a text file content using the C++.

Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.

You may also learn,

Counting the total number of words exists in a string with C++

 

Leave a Reply

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