#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();
}
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.