菜鸟请求帮忙,大虾救命

michaelkai00 2012-12-23 10:38:58
大虾,这个是我在测试输入输出流时所写的代码,功能是输入学生的成绩并保存,经过编译已经是没有任何语法问题的了,但是问题就出在我把编译窗口关了以后,想直接查看原本文件中的记录时,却没办法看了,你请问该怎么办呀?

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

class student
{
private:
long num;
string name;
float score;
public:
void setnum()
{
cout << "请输入学生的学号:" << endl;
cin >> num;
}
void setname()
{
cout << "请输入学生的姓名:" << endl;
cin >> name;
}
void setscore()
{
cout << "请输入学生的成绩:" << endl;
cin >> score;
}
long getnum()
{
return num;
}
string getname()
{
return name;
}
float getscore()
{
return score;
}
};

int main()
{
ofstream outfile("student.dat", ios::binary || ios::ate);
if (!outfile)
{
cout << "File student.dat cannot be opened." << endl;
return 0;
}
student stud[100];
char ch;
int i = 0;
while (1)
{
cout << "\n 你想输入更多的记录吗?Y/N " << endl;
cin >> ch;
if (ch == 'n' || ch == 'N')
break;
i++;
stud[i].setnum();
stud[i].setname();
stud[i].setscore();
outfile.write((char*)&stud[i], sizeof(student));

}
outfile.close();
cout << "************************输入结束***************************" << endl;
cout << "\n 你想查看文件内容吗?y/n " << endl;
cin >> ch;
if (ch == 'y' || ch == 'Y')
{
ifstream infile("student.dat", ios::binary);
if (!infile)
{
cout << "file student.dat cannot be opened." << endl;
return 0;
}
cout << "学号" << "\t学号" << "\t姓名" << "\t成绩" << endl;
i = 1;
infile.read((char*)&stud[i], sizeof(student));
while (infile)
{
cout << stud[i].getnum() << "\t";
cout << stud[i].getname() << "\t";
cout << stud[i].getscore() << "\t" << endl;
i++;
infile.read((char*)&stud[i], sizeof(student));
}
infile.close();
}
return 0;

}
...全文
110 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ILscObject 2012-12-23
  • 打赏
  • 举报
回复
这个程序每次运行时都会生成新的student.dat文件,以往的记录当然看不见了。还有就是你代码就有问题 ("student.dat", ios::binary || ios::ate);这一句应该改为 ("student.dat", ios::binary | ios::ate);
michaelkai00 2012-12-23
  • 打赏
  • 举报
回复
貌似后面添加了ios::ate就不会添加新的student.dat文件了吧?
michaelkai00 2012-12-23
  • 打赏
  • 举报
回复
谢谢哈,但是要解决我的需求应该怎么实现以上功能好呢

64,282

社区成员

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

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