Advertisement

Why doesnt this work?

Started by July 10, 2000 04:35 AM
2 comments, last by CrazyIvan 24 years, 6 months ago
Hi, i made this little program that searches a word inside a file and displays how many times it was found. But it gives me 0 every time. I would appreciate it if somebody could tell me what i''m doing wrong instead of giving the full code right away. Thx
    
// FindWord.cpp


#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main() {
	vector<string> words;
	ifstream in("FindWords.cpp");
	string word, searchWord;
	int found = 0;

	cout << "Enter the word to search for: ";
	cin >> searchWord;

	while( in >> word ) 
		words.push_back(word);

	for( int i = 0; i < words.size(); i++ ) {
		if (words<i> == searchWord) {
			found++;
		}
	}
		
	cout << "Word found " << found << " times." << endl;
}
    
seems like that code posting thingie doest work as good as i hoped

yes i did add a return after each #include and the words is words with square brackets.
Advertisement
Are you sure that your file open worked correctly.

Looking at your code, you have the file listed at the top as FindWord.cpp , but the code is trying to open FindWords.cpp.

You should perform a check to see if the file opened successfully.

        if ( !in ){    cerr << "Unable to open file." << endl;}or if ( !in.is_open() ){    cerr << "Unable to open file." << endl;}    


Also, if you are using an int mai(), you should atleast return a value.



Edited by - AlekM on July 10, 2000 9:26:02 AM
I don''t know why it doesn''t work with you, but that code works fine on my computer (using VC++ 6). For instance, if I type "#include" as the word to search for, it gives me 4 matches.
Maybe it''s because of the case sensitivity that it doesn''t find your words (#INCLUDE is not the same as #include). And the code matches only whole words (words separated by spaces and other ''strange'' characters, like ''['' and '')''). So if you''re scanning for the word ''if'', it won''t match ''ifstream''.

Dormeur.
Wout "Dormeur" NeirynckThe Delta Quadrant Development Page

This topic is closed to new replies.

Advertisement