So the homeworke ask to open a text file and count the words in that file. I got this part right but the second part im having problems with which ask to count the occurrence of a particular word in that file. the code i wrote always return 0.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
ifstream inFile;
string fileName;
string search;
string word;
int count = 0;
cout << "Please input the filename : ";
getline(cin, fileName); // input the the file path
inFile.open(fileName.c_str());
while (!inFile) // loop to ask the user to input the filename again if the file can not be found
{
cout << "ERROR:" << fileName << " can not be opened!" << endl;
cout << "Please input the filename :";
getline(cin, fileName);
inFile.open(fileName.c_str());
}
while (!inFile.eof()) // while loop to count the words
{
inFile >> word;
count++;
}
cout << "Number of white-space seperated words = " << count - 1 << endl; // output the number of words in the file
inFile.close();
cout << " input the word to search :" ;
cin >> search;
int wordcount = 0;
while (!inFile.eof()){
if (word == search){
++wordcount;
}
}
cout << " The word occured :" << wordcount << endl;
return 0;
}