修改学生记录但读取功能不起作用并且程序崩溃[重复]

问题描述 投票:0回答:0

所以这是完整的代码 在更改方法中,我读取了我需要修改的所需名称 fread 不起作用,然后程序崩溃。

#include<iostream>
#include<fstream>
using namespace std;
class student
{
    public:
    string name;
    int num;
    void enterinfo()
    {
        cout<<"ENter name"<<endl;
        cin>>name;
        cout<<"enter number"<<endl;
        cin>>num;
    }
    void showinfo()
    {
        cout<<"Name:"<<name<<endl;
        cout<<"Number:"<<num<<endl;
    }
    
    
};
class file
{
    public:
static void addtofile()
    {
        fstream add("student.dat",ios::app|ios::binary);
        if(!add)
        {
            cout<<"Error opening file";
            
        }
        student temp;
        temp.enterinfo();
        add.write((char*)&temp,sizeof(student));
        add.close();
    }
static  void showfromfile()
    {
        fstream show("student.dat",ios::binary|ios::in);
        if(!show)
        {
            cout<<"Error opening file";
            exit(1);
        }
        student temp;
        while(show.read((char*)&temp,sizeof(student)))
        {
            temp.showinfo();
        }
        show.close();
    }
static  void displayall()
    {
        student temp;
        fstream d("student.dat",ios::in|ios::binary);
        if(d)
        {
            cout<<"Error opening file";
            exit(1);
        }
        d.seekg(0,ios::beg);
        while(d.read((char*)&temp,sizeof(student)))
        {
            temp.showinfo();
            
        }
        d.close();
    }

主要错误发生在这个函数


static void change()
    {
        int count=1;
        student temp;   
        fstream change("student.dat",ios::binary|ios::in|ios::out);
        if(!change)
        {
            cout<<"Error opening file";
            exit(1);
        }
        cout<<"Enter name of student whose info you wish to change"<<endl;
        string name;
        cin>>name;
        while(change.read((char*)&temp,sizeof(temp)))
        {
            count++;
            if(temp.name==name)
            {
                break;
            }
        }   
        change.seekp((count-1)*sizeof(student),ios_base::beg);
        cout<<"ENter the new name"<<endl;
        cin>>temp.name;
        cout<<"Enter number"<<endl;
        cin>>temp.num;
        change.write((char*)&temp,sizeof(student));
        change.close();
    }
};

int main()
{
    file::addtofile();
    file::showfromfile();
    file::addtofile();
    file::showfromfile();
    file::change();
    file::displayall();
}

尝试调试并使用 ifstream 然后 fseek 成功但仍然出现错误。 非常感谢您的回复。

c++ stream file-handling seek
© www.soinside.com 2019 - 2024. All rights reserved.