0
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);
    }

}

Studentクラスには2つの関数があります:studentRegister()studentLogin()。studentRegisterが呼び出されると、学生のすべての詳細を受け入れてから、それぞれのクラスのオブジェクトをDATファイルに書き込みます。今、ログインするとき、私はファイルの内容をオブジェクト「s」に読み込もうとしています。 in.read((char *)&s, sizeof(Student));

ただし、これにより実行時エラーが発生し、コンソールが突然閉じます。何が問題になっていますか?

4

1 に答える 1

1

読み取りと書き込みは、あなたが試みているようには機能しません。これらはポインタのないクラスにのみ適していますが、文字列にはポインタがあり、クラスには文字列があるため、それらを使用することはできません。

データを読み書きするための別の方法を見つける必要があります。これの何が問題になっていますか

out << studentName << ' ' << roll << ' ' << studentPassword << '\n';

in >> studentName >> roll >> studentPassword;`

また、あなたが尋ねた質問ではinありませんが、あなたのクラスoutで宣言されるべきではありません。Studentそれらは、それらを使用する関数で宣言する必要があります。

于 2013-03-19T13:15:10.847 に答える