read total number of words from a text file

When I write my program. I can get total number of words+1. So in order to get the correct number, I have to subtract 1 from the output. So can any one suggest the improvement for my code.

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
  #include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main(){
	ifstream ins;
	int counter =0;
	char letter[40];
	
	ins.open("filename.txt");
	 if (ins.fail()){
		 cout<<"File does not open"<< endl;
	 }
	 else{
		 while (!ins.eof()){
			 ins >> letter;
			 counter++;
	 }
 }
	
	ins.close();
	cout << counter-1 ;
	return 0;
}
1. Make the 'letter' a std::string. There is no point to crash due to surprisingly long words.

2. Forget the ins.eof():
1
2
3
while ( ins >> letter ) {
  ++counter;
}
what is the reason that my code always show one more letter?
Your input data has a newline (as it should) after the last word. Whitespace at the end. Not at EOF yet. Therefore, you do (try) to read one more word and increment the counter. You don't test whether your read operation actually succeeds.

My version attempts to read a word, tests for possible failure, and thus breaks out of the loop without bogus count.
Topic archived. No new replies allowed.