Reputation: 3279
int main(){
int choice;
fstream in, out;
switch(choice)
{
case 1:
filename = s.studentRegister();
out.open(filename.c_str(), ios::out);
out.write((char *)&s, sizeof(Student));
cout<<endl<<"Registered successfully."<<endl;
case 2:
s.studentLogin();
}
}
class Student
{
std::string studentName, roll, studentPassword;
fstream in, out;
public:
std::string studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter current semester"<<endl;
cin>>ch;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
return (roll+".dat");
}
void studentLogin()
{
Student s;
cout<<"Enter roll number: "<<endl;
cin>>roll;
cout<<"Enter password: "<<endl;
cin>>studentPassword;
filename = roll + ".dat";
in.open(filename.c_str(), ios::in);
in.read((char *)&s, sizeof(Student));
read.close();
if((studentPassword.compare(s.studentPassword)==0))
{
system("cls");
cout<<"Welcome "<<s.studentName<<"!"<<endl;
displayStudentMenu();
}
else
{
cout<<"Invalid user";
exit(0);
}
}
I have two functions in my Student class: studentRegister()
and studentLogin()
. When studentRegister is invoked, it accepts all details of the student and then writes the object of the respective class to a DAT file. Now, when logging in, I'm trying to read the contents of the file into an object "s" using in.read((char *)&s, sizeof(Student));
However, this leads to a run-time error and console closes abruptly. What is going wrong?
Upvotes: 0
Views: 134
Reputation: 8027
Read and write don't work the way you are trying. They are only good for classes with no pointers, but string has pointers and your class has string so you cannot use them.
You are going to have to find a different way to read and write your data. What's wrong with this
out << studentName << ' ' << roll << ' ' << studentPassword << '\n';
and
in >> studentName >> roll >> studentPassword;`
Also not the question you asked but in
and out
should not be declared in your Student
class. They should be declared in the functions where you use them.
Upvotes: 1