Help Please ( Homework due in 5 hours )

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.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <fstream>
#include <string>
using namespace 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;
}
Last edited on
you need one of these:
 
inFile >> word;


in your last while loop i.e. your variable "word" never currently changes.
I tried that and still it doesn't work
Also on line 34 you've closed your inFile.
Oh yeah sorry about that. but still it returns 0 ;
well for starters closing the file on line 34 won't help.
then read here for a hint:
http://www.cplusplus.com/forum/beginner/30644/

(or you could close the stream like you do and then re-open. up to you)
Last edited on
yeah i closed it when i finished part 1. and now after i started to work on part 2 of the homework i forgot to remove it.
Topic archived. No new replies allowed.