#include <iostream>
#include<string.h>
#include<string.h>
void save1()
{
Student stu;
system("cls");
char c;
do { //输入学生信息
ofstream os("f1.dat", ios_base::out|ios_base::binary);//建立一个dat文件
if (!os) { //判断文件是否打开
cout << "f1.dat can not open.\n";
return;
}
system("cls");
cout << "输入你的姓名" << endl;
cin >> stu.name;
cout << "请输入你的学号" << endl;
cin >> stu.num;
cout << "请输入你的电话" << endl;
cin >> stu.tele;
os.write(reinterpret_cast<char*>(&stu), sizeof(stu));
cout << "是否继续输入,是输入y/否输入n" << endl;
cin >> c;
if (c != 'y' && c != 'n') {
cin.clear();
cin.ignore();
cout << "输入错误,请重新输入:" << endl;
cin >> c;
}
os.close();
} while (c == 'y');
menue2;
}
//查询学生信息
void search()
{
string name1,name2;
cout << "请输入你的名字" << endl;
cin >> name2;
ifstream is("f1.dat", ios_base::in | ios_base::binary);
Student stu3;
is.read(reinterpret_cast<char*>(&stu3), sizeof(stu3));
name1 = stu3.name;
if (name1.compare(name2) != 0) {
cout << "未查询到学生信息,请前往菜单2录入" << endl;
system("pause");
menue2();
}
else {
cout << stu3.num << " " << stu3.name << " " << stu3.tele << endl;
system("pause");
}
}
你把文件打开和关闭放到do...while之外,否则每次文件指针都指向文件头部,自然覆盖你之前写入的内容。