0

am trying to read characters from file but when I use end of file function it loops more than the number of character inside the file by 1 .. but I don't know why ?

#include <iostream>
#include <fstream>

int main()
{
    ifstream file;
    char ch1;
        file.open("c:\\Downloads\\test.txt" , ios::in);

    int i=0;
    while(!file.eof())
    {  i++;
        file>>ch1;
                    cout<<ch1<<endl;
          }
           cout <<i<<endl;
file.close();
return 0;
}

file contains

[]

output : [ ] ] 3

SUE
  • 81
  • 2
  • 8

2 Answers2

0

Well, when you've read the last character in the file file.eof() is still false, because the stream doesn't yet know that it's reached the end. Only after you attempt to read the already nonexistent character is eof set to true. You should probably do this

char ch;

while(file >> ch)
{
      ... 
}
Armen Tsirunyan
  • 120,726
  • 52
  • 304
  • 418
0

The reason is because just because you haven't hit the end of the file yet, doesn't mean the next read is going to succeed. Because you are reading characters, the EOF will only be set when you actually attempt to read after the last character.

In fact, even when you are reading strings, integers or other similar things out of a file there is a similar problem. At the end of many text files is an extra \n with no text after it. So when the last line is read, there is still a \n in the stream but EOF has not been set. You then proceed to read the next line which is not there whatever you are extracting into is left with the same contents as before. This results in what appears to be a duplicate reading.

Joseph Mansfield
  • 100,738
  • 18
  • 225
  • 303