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