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

tomzhch 2015-05-16 11:40:17
#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;
}

...全文
141 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2015-05-18
  • 打赏
  • 举报
回复
string是对象,不是一段内存,不适合直接读写其保存的内容,适合序列化/反序列化。
brookmill 2015-05-17
  • 打赏
  • 举报
回复
把 string m_name; 改成 char m_name[50]; 这样就好了。 string类对象的结构有点复杂,直接这样write/read是不行的。如果一定要用string,那么读写文件的方法和格式就必须改。
tomzhch 2015-05-17
  • 打赏
  • 举报
回复
引用 2 楼 brookmill 的回复:
把 string m_name; 改成 char m_name[50]; 这样就好了。 string类对象的结构有点复杂,直接这样write/read是不行的。如果一定要用string,那么读写文件的方法和格式就必须改。
这是什么原因,同样用string,使用普通对象接收时就可以,但用对象数组里的某一个元素接收时就不行
苏叔叔 2015-05-17
  • 打赏
  • 举报
回复
理解对象模型
tomzhch 2015-05-16
  • 打赏
  • 举报
回复
测试了几次,总在List函数的读操作时程序崩掉,但如果吧read函数的第一个参数换成非数组对象,如stu,运行就没问题。我用的是vs2013,不会是ide的问题吧

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧