我无法从文件中读取

I am not able to read from the file

我的问题是每当我尝试从文件中读取名称和卷号时,它只能从文件中读取卷号,请帮助我解决问题。我已经给出了我的代码 below.the 只有当我尝试从一个 class 写入文件并从另一个

读取文件时才会出现问题。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class A
{
    string name;
    int rollno;
public:
    void setdata();
    void display();
    void Check();
};

void A::setdata()
{
    cout<<"enter name"<<endl;
    cin>>name;
    cout<<"enter rollno"<<endl;
    cin>>rollno;

}

void A::display()
{
    cout<<name<<"    "<<rollno<<endl;
}

void A::Check()
{
    A a;
    ifstream file;
    file.open("aa.txt",ios::in);
    while(!file.eof())
    {
        file.read((char*)&a,sizeof(a));
        a.display();
    }
}

class B
{
public:
    void enter();

};

void B::enter()
{
    A a;
    ofstream file;
    file.open("aa.txt",ios::out);
    a.setdata();
    file.write((char*)&a,sizeof(a));
}

int main()
{
    A a1;
    B b1;
    b1.enter();
    a1.Check();
}

您不能 read/write 仅将 C++ 中的任何对象用作内存 blob。这仅适用于 POD,并且仅当该 POD 没有任何指针时才有效。您必须逐个字段实施 read/write,在 int 的情况下,您可以使用您选择的方法,但不能用于 std::string。例如,您可以存储字符串的数据大小标记,然后存储实际数据,或者您可以存储零填充的固定内存块 - 这取决于您。 例如(省略错误处理):

void A::store( std::ostream &out )
{
    int len = name.length();
    out.write( (const char *)&len, sizeof( len ) );
    out.write( name.c_str(), len );
    out.write( (const char *)&rollno, sizeof( rollno ) );
}

void A::load( std::istream &in )
{
    int len = 0;
    in.read( (char *)&len, sizeof( len ) );
    name.resize( len );
    std::copy_n( std::istream_iterator<char>( in ), len, name.begin() );
    in.read( (char *)&rollno, sizeof( rollno ) );
}

void B::enter()
{
    A a;
    a.setdata();
    ofstream file("aa.txt",ios::out);
    a.store( file );
}