When I press "2" to read the file, the data in the file can't be read although my syntax is correct. Why can't my program read the data? What is the difference between sequential and random access file and why is a random access file preferred?
void EnterRecord();
void ShowRecord();
using namespace std;
class student
{
int rollno;
string name;
int marks;
public:
void SetData();
void DisplayData();
void MainMenu();
};
void student:: MainMenu()
{
cout<<" "<<endl;
cout<<"press 1 to enter record"<<endl;
cout<<"press 2 to show record"<<endl;
}
void student::SetData()
{
cout<<"enter roll no of student"<<endl;
cin>>rollno;
cout<<"enter name of student"<<endl;
cin>>name;
cout<<"enter marks of student"<<endl;
cin>>marks;
}
void student::DisplayData()
{
cout<<rollno<<setw(10)<<setw(10)<<marks<<endl;
}
int main()
{
student s1;
int choice;
repeat:
s1.MainMenu();
cout<<"enter ur choice ::"<<endl;
cin>>choice;
switch(choice)
{
case 1:
EnterRecord();
break;
case 2:
ShowRecord();
break;
}
return 0;
}
void EnterRecord()
{
ofstream myfile;
myfile.open("student3.txt",ios::app);
int choice=1;
while(choice==1)
{
student s1;
s1.SetData();
myfile.write((char*)&s1,sizeof(student));
cout<<"press 1 to enter record again"<<endl;
cin>>choice;
if(choice!=1)
{
system("cls");
s1.MainMenu();
}
}
myfile.close();
}
void ShowRecord()
{
student s2;
ifstream myfile;
myfile.open("student3.txt");
myfile.seekg(0);
while(myfile.eof())
{
myfile.read((char*)&s2,sizeof(student));
}
s2.DisplayData();
}