program 2 is not able to delete a record which was added in program 1?

program 2 is not able to delete a record which was added in program 1? PLEASE HELP!!

PROGRAM 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class marks
{int rollno;
 float marks;
 char grade;
 public:
 void getdata()
 {cout<<"Rollno :";cin>>rollno;
  cout<<"Marks :";cin>>marks;
  if(marks>=75)
  grade='A';
  else if(marks>=60)
  grade='B';
  else if(marks>=50)
  grade='c';
  else if(marks>=40)
  grade='D';
  else grade='F';
 }
 void putdata()
 {cout<<"Rollno :"<<rollno<<"\n Marks :"<<marks<<endl;}
 int getrno()
 {return rollno;}
}m1,mrks;
void main()
{ifstream fio("marks.dat", ios::in);
 ofstream file("temp.dat", ios::out);
 int rno;
 char found='f',confirm='n';
 cout<<"Enter rollno of student  whose record is to be deleted \n";
 cin>>rno;
 while(!fio.eof())
 {fio.read((char*)&m1, sizeof(m1));
  if(m1.getrno()==rno)
  {m1.putdata();
   found='t';
   cout<<"Are you sure, you want to delete this record?(y/n)";
   cin>>confirm;
   if(confirm=='n')
   file.write((char*)&m1, sizeof(m1));
  }
  else
  file.write((char*)&m1, sizeof(m1));
 }
 if(found=='f')
 cout<<"Record no found !! \n";
 fio.close();
 file.close();
 remove("marks.dat");
 rename("temp.dat", "marks.dat");
 fio.open("marks.dat", ios::in);
 cout<<"Now the file contains\n";
 while(!fio.eof())
 {fio.read((char*)&mrks, sizeof(mrks));
  if(fio.eof()) break;
  mrks.putdata();
 }
 fio.close();
 getch();
}
Last edited on
You don't like spaces, do you?

Well, looking at the lines after line 40 you will realize that there's no code if the user confirms something else but 'n' which means the record in the file remains untouched.

Use ios::trunc to open the before you write to it. See:

http://www.cplusplus.com/reference/iostream/fstream/fstream/

If you don't create a new file you need to overwrite the old data
Topic archived. No new replies allowed.