Programme to Count the Word in a Text File | C++
Programme to Count the Word ‘THE’ in a Text File
This is the programme that you need! You need to change the terms as per your requirement.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<process.h> //For exit() purpose
void main()
{
clrscr(); //For cleaning purpose
int count=0;
char word[20]; //Assuming the longest word to be 19 characters long
ifstream fin; //Opening the file
fin.open(“The.txt”); //Open file in read mode
if(!fin)
{
cout<<”Could not open The.text file”;
exit(-1);
}
while(!fin.eof()) // To read the characters word by word
{
fin>>word;
if((strcmpi(word,”the”)==0)||(strcmpi(word,”The”)==0)) //strcmpi :- in order to ignore cases while comparing the strings
count++;
}
cout<<“Number of time ‘THE’ is present in a text file : “<<count;
fin.close(); //Closing the file
getch();
}
Here is an example as to how the above coding would get you the result . The file where the entry has been made, to count the word ‘THE’ :- There is a monkey in the zoo. The monkey was very naughty.
Result which would be shown after the above text has been read by the programme. The word ‘THE’ is present in the text for 2 times.
More Examples :
If you want to count the word monkey in the above text, you just need to write monkey in place of the in the steps :-
Instead of this : – if((strcmpi(word,”the”)==0)||(strcmpi(word,”The”)==0))
Write : – if((strcmpi(word,”monkey”)==0)||(strcmpi(word,”Monkey”)==0))
Also you need to change the ‘cout’ statement to show the number of times the word ‘THE’ is present with the word ‘MONKEY’.
Here, the result would show :- Number of time ‘MONKEY’ is present in a text file : 2
For any queries Drop Us a Message in the Comment Section
For more information Visit Our Site
If you want to submit your work Contact US