I have started working with files recently in class. When doing my homework, I can't really understand .eof().
The program which we are coding should do the following: the program asks you for a file name, opens it, and reads every character and counts every word. In the end it shows the average length of the words.
What happens is:
Whenever I open a file with a text that ends with a dot, it works correctly, the average is correct. However, when the text does not end with a dot (for example: 9 8 7 6 5 4 3 2 1 Ignition), it shows that there are no words.
I've been searching through the internet and I've only found that the End of File constant is normally -1
. I'm just trying to figure out how it works. Thanks
The code is the following:
bool isSeparator (char lletra){ //Com que són caràcters anglesos no hem de tenir en compte els accents
//Pre: cert
//Post: retorna cert si lletra és un separador, fals altrament -- els números són entesos com separadors
bool separador = true;
if(lletra>='a' and lletra<='z')
separador = false;
else if(lletra>='A' and lletra<='Z')
separador = false;
else {
separador = true;
}
return separador;
}
void calculateNumbers (string fileName){
ifstream openFile (fileName.c_str());
char lletra; //Iniciem la primera variable
openFile>>lletra;
double wordCounter, average, wordLength, totalLength;
char auxiliar = ' ';
wordCounter = average = wordLength = totalLength = 0;
while (not openFile.eof()){ //Mentre no trobi el final, que continui mirant lletres
if (not isSeparator(lletra)){
wordLength++;
auxiliar = lletra;
} else if (isSeparator (lletra) and not isSeparator(auxiliar)){
wordCounter++;
totalLength+=wordLength;
wordLength = 0;
auxiliar = lletra;
}
openFile>>lletra;
}
cout<<setprecision(3);
cout<<fixed;
average = totalLength/wordCounter;
if (average==0){
cout<<"Mitjana longitud mot: cap mot!";
} else {
cout<<totalLength<<" "<<wordCounter<<endl;
cout<<"Mitjana longitud mot: "<<average<<endl;
}
cout<<openFile.eof();
}
Some of the things are in catalan. If there's anything you don't understand just ask me.