C++ Program to Count Occurrence of a Word in a Text File

This C++ program will read  a word from user and then count its total occurrence in a text file “my_data.txt”. Make sure you have already create this text file and have some text in it. Place this file in the same directory where your program source file is present.

#include<iostream.h>
#include<fstream.h>
#include<string.h>
 
 
int main()
{
 ifstream fin("my_data.txt"); //opening text file
 int count=0;
 char ch[20],c[20];
 
 cout<<"Enter a word to count:";
 gets(c);
 
 while(fin)
 {
  fin>>ch;
  if(strcmp(ch,c)==0)
   count++;
 } 
 
 cout<<"Occurrence="<<count<<"n";
 fin.close(); //closing file
 
 return 0;
 
}

C++ Program to Count Occurrence of a Word in a Text File

11 thoughts on “C++ Program to Count Occurrence of a Word in a Text File”

    1. #include

      using namespace std;
      int main()
      {
      char c[] = “C++ programming is not easy.”, check = ‘m’;
      int count = 0;

      for(int i = 0; c[i] != ‘\0’; ++i)
      {
      if(check == c[i])
      ++count;
      }
      cout << "Frequency of " << check << " = " << count;
      return 0;
      }

  1. write a program that ask the user for the name of a file name assume the file contains a series of numbers each written on a seperate line the program should read the contents of file into an array and then display sum of these numbers
    can you please solve it for me

  2. So what is strcmp ? Is it compare? When i play with c or c++ i atend to write functions that already exist. I spend all the time writing the function .

  3. This program wont work if a fullstop comes after the word that is to be searched. As full stop would come inside the string that is being compared.
    Example:
    My Name Is Rohan.
    And word searched is rohan
    Then count would appear 0.

Leave a Comment

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