character count in file

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;






Last edited on
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++;
        }
    }
Last edited on
as u suggested i did this

while(!fin.eof())
{
while(fin.get(ch))
{
if(ch!='\n')
{
count++;
}
}
}
it worked but please can you tell me how did it worked...
as u suggested i did this

while(!fin.eof())


No.
That is not what I suggested.

The loop while (fin.get(ch)) will read the entire file one character at a time. You don't need the eof() loop at all. Delete it.

At the end of the file, several flags are set, not just eof. The suggested code is equivalent to testing !fin.fail()



thanku sir i understand it know ......

One question my program was giving 1 extra value was it due to eofbit,failbit e.t.c
Ok let me try to explain in more detail.

The original code:
1
2
3
4
5
6
7
8
    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.

Topic archived. No new replies allowed.