Function Question

In this program, it's supposed to read data from a file, prompt user for a word to search -like google- count the total words and number of occurrences that the word appeared. Everything works fine and dandy except the function that counts the number of occurrences - returnParticularWord. It keeps returning a zero value, and for the life of me, I don't know why.
Please, any help would be greatly appreciated.

The code is below:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

//Function Protorypes
void getInputFile(ifstream & in, string & filename);
int returnTotalWordsInFile(ifstream & in);
int returnNumberOfParticularWord(ifstream & in, string & filename, string & word);

int main ()
{
//Prompt user for file input
ifstream in;
cout<<"Please enter the name and full path of the file that you would"<<endl;
cout<<"liked to be searched: "<<endl;
string filename;

//First function. This is the one that is getting skipped for some reason.
getInputFile(in, filename);


//Initializing variables
string text;
in>>text;
string word = "";
//Prompt user for the selected word.
cout<<"Please enter the word that you want to search"<<endl;
cout<<"(Only in lowercase): "<<endl;
cin>>word;


int total = returnTotalWordsInFile(in);
int select = returnNumberOfParticularWord(in, filename, word);
cout<<"The total number of words in the file is "<<total<<endl;
cout<<"Your word appears "<<select<<" times."<<endl;

double relevancy = ((1.0*select)/(1.0*total))*100;
cout<<"Your relevancy rating is "<<fixed<<setprecision(1)<<relevancy<<" %."<<endl;



return 0;
}

void getInputFile(ifstream & in, string & filename)
{
//Open the selected filename.

getline(cin, filename);
in.open(filename.c_str());

//Validate user's input
while(!in)
{
cout<<"Error opening file."<<endl;
cout<<"Enter the name and path of the file: ";

getline(cin, filename);
in.open(filename.c_str());
}

}

int returnTotalWordsInFile(ifstream & in)
{
//Initialize variables

int count = 0;
string text;

//Create loop that will count all of the words in the file
while(in)
{
//While counting the words, initiate search of the word in the file.

count++;
in>>text;

}
//Print output


in.close();
return count;

}

int returnNumberOfParticularWord(ifstream & in, string & filename, string & word)
{


getline(cin, filename);
in.open(filename.c_str());

string text;
in>>text;
int occurences = 0;
while(in)
{


//Initiate variables

if(text==word)
{
//Count the occurences of the selected word
occurences++;
}

in>>text;
}
//Print the output
in.close();
return occurences;
}

Thank you in advance,
Chris
I assume that since eof was reached in returnTotalWordsInFile, returnNumberOfParticularWord doesn't get to read anything at all. See http://www.cplusplus.com/reference/iostream/istream/seekg/
Also, when posting code, use [code] tags.
Topic archived. No new replies allowed.