Code Bye

c++文件操作中对二进制文件进行读操作的问题

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class CStudent
{
public:
	string  m_name;
	double m_score[3];
	double m_aver;

	CStudent();
	bool Setdata();
	void Output();
	void Aver();
};
CStudent::CStudent()
{
	m_aver = 0;
	//memset(m_name, 0, 10);
}
void CStudent::Aver()
{
	m_aver = (m_score[0] + m_score[1] + m_score[2]) / 3;
}
bool CStudent::Setdata()
{
	return bool(cin >> m_name >> m_score[0] >> m_score[1] >> m_score[2]);
	//Aver();
	//return 0;

}
void CStudent::Output()
{
	cout << m_name << m_score[0] << m_score[1] << m_score[2] << m_aver << endl;
}
class CStuFile
{
	CStudent st[100];
	CStudent stu;
	ifstream infile;
	ofstream outfile;
public:
	int AddTo();
	int List();
	void Sort();
};
int CStuFile::AddTo()
{
	outfile.open("students.dat", ios::out | ios::binary);
	if (!outfile)
	{
		cout << "open error!" << endl;
		return 0;
	}
	while (stu.Setdata())//cin >> stu.m_name >> stu.m_score[0] >> stu.m_score[1] >> stu.m_score[2]
	{
		outfile.write((char *)& stu, sizeof(stu));
	}
	outfile.close();
	return 1;
}
int CStuFile::List()
{
	int p;
	int i = 0;
	//CStudent s[10];
	infile.open("students.dat", ios::in | ios::binary);
	if (!infile)
	{
		cout << "open error!" << endl;
		return 0;
	}
	while (infile.read((char *) &st[i], sizeof(st[i])))
	{

		//st[i] = stu;
		cout << st[i].m_name << st[i].m_aver << endl;
		++i;
	}

	int j = i;
	infile.close();
	outfile.open("students scroe.dat",ios::out|ios::binary);
	if(!outfile)
	{
	cout << "open error!" <<endl;
	infile.close();
	return 0;
	}
	for(i = 0; i< j; ++i)
	{
	outfile.write( (char * ) & st[i], sizeof(st[i]) );
	}
	outfile.close();
	return 1;
}
int main()
{
	CStuFile sf;
	sf.AddTo();
	sf.List();
	return 0;
}
测试了几次,总在List函数的读操作时程序崩掉,但如果吧read函数的第一个参数换成非数组对象,如stu,运行就没问题。我用的是vs2013,不会是ide的问题吧
30分
把 string  m_name;
改成 char  m_name[50];
这样就好了。

string类对象的结构有点复杂,直接这样write/read是不行的。如果一定要用string,那么读写文件的方法和格式就必须改。

引用 2 楼 brookmill 的回复:

把 string  m_name;
改成 char  m_name[50];
这样就好了。

string类对象的结构有点复杂,直接这样write/read是不行的。如果一定要用string,那么读写文件的方法和格式就必须改。

这是什么原因,同样用string,使用普通对象接收时就可以,但用对象数组里的某一个元素接收时就不行

理解对象模型
10分
string是对象,不是一段内存,不适合直接读写其保存的内容,适合序列化/反序列化。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c++文件操作中对二进制文件进行读操作的问题