word search

can anyone help me figure out why this is not working. its a program that reads a file and searches for a specific word. i can get the total number of words in file to return correctly. but my Occurences variable is giving me some trouble in my returnNumberOfParticularWord function. it returns 0. also i need my program to stay in a loop if file path entered is not correct in my void getInputFile function. thanks

[
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;

//prototypes
void getInputFile(ifstream & in, string & FileName);
int returnTotalWordsInFile(ifstream & in);
int returnNumberOfParticularWord(ifstream & in, const string & wrd);

int main()
{
int WordCounter = 0;
int Occurences = 0;
ifstream in;
string FileName;

getInputFile(in, FileName);

string text;
string word = "";
cout<<"Please enter the word that you want to search, in lower case only."<<endl;
getline(cin,word);
int WordCounter = returnTotalWordsInFile(in);
int Occurences = returnNumberOfParticularWord(in, word);
cout<<"The total number of words in the file is "<<WordCounter<<endl;
cout<<"Your word appears "<<Occurences<<" times."<<endl;
double relevancy = ((1.0*Occurences)/(1.0*WordCounter))*100; cout<<"Your relevancy rating is "<<fixed<<setprecision(1)<<relevancy<<" %."<<endl;
system("pause");
in.close();
return 0;
}
void getInputFile(ifstream & in, string & FileName)
{

bool done = true;

while(done)
{
cout<<"Enter full name of file path of which file is to be read from."<<endl;
getline(cin,FileName);
ifstream testStream;
testStream.open(FileName.c_str());
testStream.close();
if(testStream.fail())
{
cout<<"File does not exist!\n";
cout<<"Enter full name of file path of which file is to be read from."<<endl;
cin.clear();
cin.ignore(1000, '/n');
done = false;
}
else
{
in.open(FileName.c_str());
done = true;
}
}
}

int returnTotalWordsInFile(ifstream & in)
{
string text;
int WordCounter = 0;
while (in)
{
WordCounter++;
}
in>>text;
in.close();
return WordCounter;
}

int returnNumberOfParticularWord(ifstream & in, string & FileName, string & word)
{
int Occurences = 0;
while(in)
{
if (text == word)
{
Occurences++;
}
in>>text;
}

in.close();
return Occurences;
}
]
Last edited on
Welcome, read before posting.

http://www.cplusplus.com/forum/beginner/1/

First, wrap your code in [code ] [ /code] tags, and then please phrase precisely what is not working as you expect which means, which part doesn't work, what it should do, and what it does right now instead.
Last edited on
Topic archived. No new replies allowed.