Help me out with this program!!

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
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
class STUDENT
{
 char name[40];
 char grade;
 int roll;
 public:
 void getdata()
 {
  char ch;
  cin.get(ch);
  cout<<endl<<"Enter the name of the student-->";
  cin.getline(name,40);
  cout<<endl<<"Enter the student's grade-->";
  cin>>grade;
  cout<<endl<<"Enter the student's roll number-->";
  cin>>roll;
 }
 void display()
 {
  cout<<endl<<"Student's name-->"<<name;
  cout<<endl<<"Student's roll no.-->"<<roll;
  cout<<endl<<"Student's grade-->"<<grade;
 }
 main()
 {
  system("cls");
  STUDENT dx[3];
  fstream fin;
  fin.open("student.dat",ios::in|ios::out);
  cout<<"Please enter the data for stuents.";
  for(int i=0;i<3;i++)
  {
   dx[i].getdata();
   fin.write((char*)&dx[i],sizeof(dx[i]));
  }
  fin.seekg(0);
  cout<<"The students in our database are given below..";
  cout<<endl;
  for(i=0;i<3;i++)
   {
   fin.read((char*)&dx[i],sizeof(dx[i]));//error
   dx[i].display();
   }
   fin.close();
 getch();
}

Visit for the error and snip.
https://drive.google.com/file/d/0ByQH6SasL4r4dl9XSzVXZldnTVE/view?usp=sharing
Last edited on
closed account (48T7M4Gy)
line 44: int i
Yes Kemort you are right but why do I have to declare it for the second time.
Also, I didn't nterminate the class.
Last edited on
closed account (48T7M4Gy)
It's all to do with 'scope'.
To elaborate on kemort's answer, when you declare a variable in a for statement like you do in line 36, the scope of the variable is that for loop only. If you want to use a variable of the same name in another loop, you need to declare it again.
Thanks #MikeyBoy I got it now!!
Topic archived. No new replies allowed.