can anyone please tell me why is the second program not able to show the records which were entered in the first program??
PROGRAM 1 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include<fstream.h>
#include<conio.h>
void main()
{clrscr();
ofstream fileout;
fileout.open("marks.dat", ios::app);
char ans='y';
int rollno;
float marks;
while(ans=='y')
{
cout<<"\n Enter Rollno. :";
cin>>rollno;
cout<<"\n Enter Marks :";
cin>>marks;
fileout<<rollno<<'\n'<<marks<<'\n';
cout<<"\n Want to enter more records?(y/n)";
cin>>ans;
}
fileout.close();
getch();
}
|
PROGRAM 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include<fstream.h>
#include<conio.h>
struct marks
{
int rollno;
float marks;
}m1;
void main()
{clrscr();
int rn;
char found='n';
ifstream fi("MARKS.DAT", ios::in);
cout<<"Enter Rollno to be searched for :";
cin>>rn;
while(!fi.eof())
{
fi.read((char*)&m1, sizeof(m1));
if(m1.rollno==rn)
{
cout<<"Rollno"<<rn<<"has"<<m1.marks<<"% marks."<<endl;
found='y';
break;
}
}
if(found=='n')
cout<<"Rollno not found in file!!"<<endl;
fi.close();
getch();
}
|
Last edited on
That's not going to work.
Each data struct was saved as two lines of text
fileout<<rollno<<'\n'<<marks<<'\n';
But you are trying to re-read it as a binary block (size of a marks structure)
fi.read((char*)&m1, sizeof(m1));
The two methods are incompatible.
Last edited on
how should i re-read the records entered in PROGRAM 1?
Well if you use formatted output ( outputfile << ) then use formatted input (inputfile >>);
1 2 3 4 5 6
|
while(!fi.eof())
{
fi >> mi.rollno >> mi.marks; //read in a pair of formatted inputs
if(m1.rollno==rn)
{
|
Last edited on