Word count?

I need help understanding a problem. For a homework assignment I need to create a word counter using a string variable and a .txt file. I am using Dev-C++ and this is what I have so far:

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

using namespace std;

int main()
{
    // Variable declarations:
    ifstream InData;
    string Everything, FileName;
    int counter;
    
    do{//Restart loop
    
    counter=0;
    
    //Input prompt:
    cout<<"Please enter a file name(enter \"quit\" to quit): ";
    cin>>FileName;
    
    if(FileName != "quit"){//Skips processing if quit is entered
    
    InData.open(FileName.c_str());
    
    //Data validation:
    while(!InData){
    cout<<"Cannot find file... please retype: ";
    cin>>FileName;
    InData.open(FileName.c_str());
    }
    
    //Processing:
    do{
    counter++;
    InData>>Everything;
    }while(InData);
    
    InData.close();
    InData.clear();
    
    //Output:
    cout<<"There are "<<counter<<" words in the file."<<endl;
    }
    }while(FileName!="quit");
    
    system("PAUSE");
    return 0;
}

Every time I test it I get 1 more word then there actually are. I can simply just start the counter at -1 but that doesn't seem logical. I tried forming the processing loop in all the ways I could but I keep on getting the same problem.
Could somebody please explain to me why this is happening? I don't need you to give me the answer but maybe just explain the problem?

Thank you in advance.
Last edited on
1
2
3
4
 do{
		counter++;
		InData>>Everything;
    }while(!InData.eof());
Ok thank you, but what was happening in my earlier code that caused it to count an extra word?
Make sure that there is a word before counting it.
Suppose an empty file.
Ok I see! Thank you very much!
Topic archived. No new replies allowed.