| niksri4 (2) | |
|
#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++????? | |
|
|
|
| Peter87 (3687) | |||
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.
| |||
|
|
|||
| niksri4 (2) | |
| thanks peter87 | |
|
|
|