Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have written a code to retrive data from a file in
C++,as followscStud S;
while(!f.eof())
{
f.read((char*)&S,sizeof(S));
coutS;
}where cStud is any class of mine and f is an object of ifstream.
The problem i am facing is that it prints the last record twice.
But if i write the code as follows there is no problemcStud S;
while( f.read((char*)&S,sizeof(S)))
{
coutS;
}Where is the problem in the previous code,its urgent

=================================================
This can happen if the data being read into your variables data type differs from that of the file itself. A string read with a char * that doesn't contain an EOL or null terminated string can confuse the cout function (I'm assuming that their is a space between the cout function and your S variable). Without seeing the information withing the file itself it is difficult to say. Is the data text or binary? If binary, is it string or character (yes there is a difference).borelli35

This is an easy and common beginner problem.
Let's walk thru this code, starting at the top of the loop and just after the last record was read and output (so the next read will find the end of file).
while(!f.eof())
{
f.read((char*)&S,sizeof(S));
coutS;
}
- f.eof() will return false because the last read did not find end of file, so the loop continues- f.read() will attempt to read a record but will find end of file
- the cout outputs the contents of S (which are the contents of the last successful read)
- FINALLY, f.eof() is check, found to be true and then the loop quits.
The problem is that the loop is coded such that there is a cout between the execution of the f.read() and the test of f.eof().
One solution is to do a primer read before the loop and then reorder the two statements inside the loop. You need to check for eof immediately after reading.f.read(....);
while(!f.eof())
{
cout S;
f.read((char*)&S,sizeof(S));
}

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |