#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; }
Enter a word to count: World Occurrence= 3
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.