问题代码:
#include<iostream>
#include<fstream>
using namespace std;
#define num 10
void CreateBiFile(string filename);
void ReadBiFile(string filename);
class Student
{
string number;
string name;
string sex;
int score;
public:
Student(string nu = "", string na = "", string se = "", int s= 0);
friend ostream& operator<<(ostream& out, const Student& s);
};
Student::Student(string nu, string na, string se, int s) //构造函数
{
number = nu;
name = na;
sex= se;
score = s;
}
ostream& operator<<(ostream& out, const Student& s) //重载输出运算符<<
{
cout << s.number << " " << s.name << " " << s.sex << " " << s.score << endl;
return out;
}
int main()
{
CreateBiFile("stu.dat");
ReadBiFile("stu.dat");
return 0;
}
void CreateBiFile(string filename)
{
ofstream out(filename,ios::binary);
Student stu[3] = { Student("B21030209","jr","male",100),Student("B21030210","pyy","male",100),Student("B21030212","nysq","male",100) };//对象数组的初始化
out.write((char*)stu,sizeof(Student)*3); //两个实在参数自己填写
out.close();
}
void ReadBiFile(string filename)
{
Student stu[num] = {};
int i = 0;
ifstream in(filename,ios::binary);
while (!in.eof()) //读出记录并显示
{
in.read((char*)&stu[i++], sizeof(Student));
}
for (int j = 0; j < i - 1; j++)
{
cout << stu[j];
}
//exit(1);
in.close();
}
?关文件那边出现了问题!
?解释:
修改后的代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const int num = 10;
void CreateBiFile(const char* filename);
void ReadBiFile(const char* filename);
class Student
{
char* number;
char* name;
char* sex;
int score;
public:
Student(const char* nu = "", const char* na = "", const char* se = "", int s= 0);
friend ostream& operator<<(ostream& out, const Student& s);
};
Student::Student(const char* nu, const char* na, const char* se, int s) //构造函数
{
number = new char[strlen(nu)+1];
name = new char[strlen(na)+1];
sex = new char[strlen(se)+1];
strcpy(number,nu);
strcpy(name,na);
strcpy(sex, se);
score = s;
}
ostream& operator<<(ostream& out, const Student& s) //重载输出运算符<<
{
cout << s.number << " " << s.name << " " << s.sex << " " << s.score << endl;
return out;
}
int main()
{
CreateBiFile("stu.txt");
ReadBiFile("stu.txt");
return 0;
}
void CreateBiFile(const char* filename)
{
ofstream out(filename,ios::binary);
Student stu[3] = { Student("B21030209","jr","male",100),Student("B21030210","pyy","male",100),Student("B21030212","nysq","male",100) };//对象数组的初始化
out.write((char*)stu,sizeof(Student)*3); //两个实在参数自己填写
out.close();
}
void ReadBiFile(const char* filename)
{
Student stu[num];
int i = 0;
ifstream in(filename,ios::binary);
while (!in.eof()) //读出记录并显示
{
in.read((char*)&stu[i++], sizeof(Student));
}
for (int j = 0; j < i - 1; j++)
{
cout << stu[j];
}
in.close();
}
?其他感悟:
在用到文件的read()读取类的函数时,尽量用char型数组,不用string类型。
|