本人计算机专业新生,麻烦各位帮忙看一下这段c++代码的文件输入输出部分问题在哪
在定义的file_input函数中,通过传入一个类,以二进制的形式存入文件。
在主函数中,我根据输入的信息动态生成类,用以存储这些信息,并将该类通过调用file_input函数以二进制存入文件中,如此循环直到输入为-1
在file_output函数中,从二进制文件中提取类并调用函数输出信息
但是这样无法将类正确地存入文件中,且输出为乱码,想问一下为什么会出现这种情况,以及如何修正
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
class student
{
public:
student();
student(int id, string name, float grade);
student(const student &s);
void print_stu();
//friend void delete_stu(student *s);
//friend void modify_stu(student *s);
private:
int id;
string name;
float grade;
};
student::student()
{
}
student::student(int id, string name, float grade)
{
this -> id = id;
this -> name = name;
this -> grade = grade;
}
student::student(const student &s)
{
id = s.id;
name = s.name;
grade = s.grade;
}
void student::print_stu()
{
cout << "ID: " << id << " " << "Name: " << name << " " << "Grade: " << grade << endl;
}
void file_input(student s)
{
s.print_stu();
fstream file1;
file1.open("student.dat", ios::out | ios::binary | ios::app);
if(!file1)
{
cout << "Cannot open the file" << endl;
abort();
}
file1.write((char *)&s, sizeof(s));
file1.close();
}
void file_output()
{
fstream file1;
file1.open("student.dat", ios::in | ios::binary);
if(!file1)
{
cout << "Cannot open the file" << endl;
abort();
}
student s;
while(file1.read((char *)&s, sizeof(s)))
{
s.print_stu();
}
file1.close();
}
int main()
{
while(1)
{
cout << "1: 输入学生信息" << endl << "2: 显示学生信息" << endl;
int control = -1;
cin >> control;
if(control == 1)
{
cout << "请输入学生id, 以-1停止输入" << endl;
int id = 0;
cin >> id;
while(id != -1)
{
cout << "请输入学生姓名,成绩" << endl;
string name;
float grade;
cin >> name >> grade;
student *s_ptr = new student(id, name, grade);
file_input(*s_ptr);
delete s_ptr;
s_ptr = NULL;
cout << "请输入学生id, 以-1停止输入" << endl;
cin >> id;
}
cout << "输入成功!" << endl;
}
if(control == 2)
{
file_output();
}
}
}