repeat reading of last data

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
#include<process.h> //for exit(0)
#include<stdio.h>
struct student
{ clrscr();
char n[111];
int a;
};
student s;

void main()
{clrscr();
int n;
char c;
fstream sfile;
cout<<"CHOICE :";
cin>>c;
if(c=='y')
{sfile.open("stud.dat",ios::out);

cout<<"Enter no. of student Data";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"\nName: ";
gets(s.n);
cout<<"age: ";
cin>>s.a;
sfile.write((char*)&s,sizeof(s));
}

sfile.close();exit(0);
}
else{
cout<<"\nDisplay Students Details";
sfile.open("stud.dat",ios::in);

while(sfile)
{
sfile.read((char*)&s,sizeof(s));
cout<<"\nName ";
puts(s.n);
cout<<"Age "<<s.a;
}
sfile.close();
}
getch();
}



why sfil is reading last recorded data twice in turbo c++?????
sfile will not enter the error state until a read operation has failed. That means that when all the data has been read, the loop while(sfile) runs one more time. sfile.read((char*)&s,sizeof(s)); fails, leaving s unchanged, so the same data is printed twice. To fix this you should put the read operation as the loop condition.
1
2
3
4
5
6
while(sfile.read((char*)&s,sizeof(s)))
{
	cout<<"\nName ";
	puts(s.n);
	cout<<"Age "<<s.a;
}
thanks peter87
Topic archived. No new replies allowed.