C++ program to count the number of sentences from a text file

In this tutorial, we’ll learn how to count the number of sentences from a text file using C++ programming language. Here the text file name can be anything as per the user wish. But the text file should contain some content with few sentences.

For better understand, let us see an example

Hi all, Hope everyone are doing good. Welcome to CodeSpeedy. It is the platform for all the learners.

Let the file contain the above content in .txt format.

Output: The number of sentences is 3

How to count the number of sentences from a .txt file

In this program we use file handling functions such as ifstream. It is used to read the data from the file. We also use getline() function here. The getline() is a standard library function. It reads the string from the input stream.

Now, let us see the program for counting the number of sentences from a .txt file.


#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
  ifstream file("xyz.txt",ios::in);
  string curr;
  int count=0;
  while(getline(file, curr))
    for(int i=0;i<curr.size();i++)
      if(curr[i]=='.' || curr[i]=='?' || curr[i]=='!')
  cout<<"The total number of sentences are: "<<count<<"\n";
  return 0;


The totalĀ  number of sentences are: 5

Hope, you have understood how our program works. For better understand kindly follow the below attached links.

Leave a Reply

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