文件的输入输出问题

garkfbiafiaala 2014-04-23 09:46:03
我定义了一个学生类,我想把我从键盘输入的学生对象的信息保存在一txt文件中,然后在我关闭程序后再次打开时,可以按名字或学号索引把我指定的学生信息输出到屏幕上,这要怎么实现才行
...全文
103 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2014-04-24
  • 打赏
  • 举报
回复


#include<iostream>
#include<fstream>
#include<string>
using namespace std;

class Student{
public:
    string name;
    int age;
};
int main() {

Student stu1,stu2,stu3;
stu1.name="David";
stu1.age =20;
stu2.name="John";
stu2.age =22;
stu3.name="Lily";
stu3.age =19;

ofstream outfile("I:\\stu.dat",ios::binary);
outfile.write((char*)&stu1,sizeof(stu1));//写入数据到文件
outfile.write((char*)&stu2,sizeof(stu2));
outfile.write((char*)&stu3,sizeof(stu3));
outfile.close();


ifstream infile("I:\\stu.dat",ios::binary);
Student stu4,stu5,stu6;
infile.read((char*)&stu4,sizeof(stu4));
infile.read((char*)&stu5,sizeof(stu5));
infile.read((char*)&stu6,sizeof(stu6));

cout<<stu4.name<<" "<<stu4.age<<endl;
cout<<stu5.name<<" "<<stu5.age<<endl;
cout<<stu6.name<<" "<<stu6.age<<endl;
infile.close();

return 0;
}

/*
David 20
John 22
Lily 19

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.
*/

赵4老师 2014-04-24
  • 打赏
  • 举报
回复
fprintf fscanf
「已注销」 2014-04-24
  • 打赏
  • 举报
回复
那是一个对象,肯定是乱码
garkfbiafiaala 2014-04-24
  • 打赏
  • 举报
回复
引用 5 楼 zhangyonghui2117 的回复:


#include<iostream>
#include<fstream>
#include<string>
using namespace std;

class Student{
public:
    string name;
    int age;
};
int main() {

Student stu1,stu2,stu3;
stu1.name="David";
stu1.age =20;
stu2.name="John";
stu2.age =22;
stu3.name="Lily";
stu3.age =19;

ofstream outfile("I:\\stu.dat",ios::binary);
outfile.write((char*)&stu1,sizeof(stu1));//写入数据到文件
outfile.write((char*)&stu2,sizeof(stu2));
outfile.write((char*)&stu3,sizeof(stu3));
outfile.close();


ifstream infile("I:\\stu.dat",ios::binary);
Student stu4,stu5,stu6;
infile.read((char*)&stu4,sizeof(stu4));
infile.read((char*)&stu5,sizeof(stu5));
infile.read((char*)&stu6,sizeof(stu6));

cout<<stu4.name<<" "<<stu4.age<<endl;
cout<<stu5.name<<" "<<stu5.age<<endl;
cout<<stu6.name<<" "<<stu6.age<<endl;
infile.close();

return 0;
}

/*
David 20
John 22
Lily 19

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.
*/

怎么我打开那个stu.dat,里面是一堆乱码的
baichi4141 2014-04-24
  • 打赏
  • 举报
回复
首先,你要学会把从输入的信息保存到内存里 然后,你要学会把内存中的信息保存到文件里 然后,你要学会把文件中的信息读取到内存里 然后,你要学会把内存中的信息显示到屏幕上 最后,你要学会按某种索引找到内存中的信息
garkfbiafiaala 2014-04-24
  • 打赏
  • 举报
回复
引用 1 楼 zhangyonghui2117 的回复:
io流操作,将对象以二进制保存,然后再读取
能再具体点吗
「已注销」 2014-04-23
  • 打赏
  • 举报
回复
io流操作,将对象以二进制保存,然后再读取

64,645

社区成员

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

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