The question is to count characters of file....My code is giving one extra even when its not counting "end of line character"...please help me correct it...
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
ifstream fin;
ofstream fout;
char ch;
int count=0;
fin.open("file.txt");
if(fin.is_open())
{
while(!fin.eof())
{
fin.get(ch);
if(ch!='\n')
{
count++;
}
}
}
else
{
cout<<" Error in opening file ";
}
fout.open("fileOutput.txt");
fout<<count;
It is best to avoid using eof() as the loop condition.
In some circumstances it is unreliable (some error may occur instead of eof) and it also lends itself to logic errors of this kind:
1 2 3 4 5 6 7 8
while (!fin.eof())
{
fin.get(ch);
if (ch!='\n')
{
count++;
}
}
At line 4, the code never checks that the input succeeded or failed.
Better to test whether the input succeeded in the while loop condition itself. That way the body of the loop is entered only when the input worked.
1 2 3 4 5 6 7
while (fin.get(ch))
{
if (ch!='\n')
{
count++;
}
}
while (!fin.eof())
{
fin.get(ch);
if (ch!='\n')
{
count++;
}
}
Assume everything is going along smoothly, characters are being read one at a time from the file.
Then we get to line 3 to read the very last character. fin.get(ch);
that was ok, ch now contains the last character in the file. No flags were set. The count is incremented (assume it was not a '\n').
Control goes back to the start of the loop, line 1. the eof flag is not yet set. So the loop is executed again. This time the fin.get() cannot read a character. The end of file has been reached. eof is set. fail is set.
But there is no check here.
Execution continues to the next line and count is incremented again - because ch remains unchanged from the previous time.
So the reason for the incorrect result is the logic error. After doing fin.get() there was no test on whether or not it succeeded and by the time the eof flag is set the loop has already executed one time too many.