Trouble with Functions

Ok so im sure im doing something stupid :D

i have a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int wordFunc(string a){
	std::ifstream inp;
	inp.open(a, std::ios::in);
	if (inp.is_open()){
		std::string word;
		unsigned long wordCount = 0;
		while(!inp.eof()){
			inp >> word;
			while(word.length() > 0){
				wordCount++;
			}
			inp.close();
		}
		return wordCount;
	}
}


the string is a user input file.txt - its set to be C:\Dump\user.txt right now

when i call the code with:

1
2
3
4
5
6
7
8
9
10
11
12
int main(){
	string file;
	int words = 0;
	file = "C:\\Dump\\user.txt";
	
	int a = wordFunc(file, words);
	cout << "Words: " << a << endl;
	
	system("PAUSE");
	return 0;
}


The console just halts - I havnt coded anything in C++ in many a year so im definitely rusty - any help?
The endless loop is this:
1
2
3
while(word.length() > 0){
    wordCount++;
}

incrementing wordCount won't change word.length()

There was some redundant code. You could have simply written

1
2
3
4
5
6
7
8
9
10
unsigned long wordFunc(const std::string& a){
    std::ifstream inp(a);
    unsigned long wordCount = 0;
    std::string word;
    while(inp >> word)
    {
        wordCount++;
    }
    return wordCount;
}


or, for extra finesse,

1
2
3
4
5
6
std::size_t wordFunc(const std::string& a)
{
    std::ifstream inp(a);
    std::istream_iterator<std::string> beg(inp), end;
    return distance(beg, end);
}


Last edited on
Yea i was just coming back to post about the infinate loop - knew it was something simple - thanks for the cleaner code too !!!
Topic archived. No new replies allowed.