2013-03-19 114 views
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); 
    } 

} 

我在学生课中有两个功能:studentRegister()studentLogin()。当调用studentRegister时,它接受学生的所有细节,然后将相应类的对象写入DAT文件。现在,在登录时,我尝试使用in.read((char *)&s, sizeof(Student));如何将一个类的对象传递给同一个类的函数?

将文件内容读入对象“s”。但是,这会导致运行时错误并且控制台突然关闭。出了什么问题?

+3

正如您在另一个问题中提到的,您无法用这些方法编写和阅读您的课程。 (此外,问题标题与实际问题没有任何关系。) – 2013-03-19 13:01:18

+0

请提供*短*,*完整*示例程序。有关更多详细信息,请参阅http://SSCCE.org。 – 2013-03-19 13:09:02

回答

1

阅读和写作不按照您尝试的方式工作。它们只适用于没有指针的类,但字符串有指针,而你的类有字符串,所以你不能使用它们。

您将不得不寻找一种不同的方式来读取和写入您的数据。有什么问题你问,但inout不应该在你的Student类中声明该

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

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

也没有问题。他们应该在你使用它们的功能中声明。

+0

非常感谢!我在文件中存储了多个字符串,并且不知道如何随机访问它们(不使用seekg())。在工作正常。顺便说一句,可以在DAT和二进制文件中正确读取,或只是文本文件? – Quoyo 2013-03-19 13:35:26

+0

Read将从任何类型的文件中读取字节,并且写入将把字节写入任何类型的文件。问题是你有其他的东西。也就是说,你不能将字符串(或你的学生)这样的对象视为平坦的字节序列。他们有内部结构(使用指针等),读写一无所知。 – john 2013-03-19 13:45:28

相关问题