码
#include<iostream>
#include<fstream>
#include<conio.h>
#include<string>
using namespace std;
class student
{
int admno;
char name[20];
// char address[20];
//string name;
public:
void getdata()
{
cout<<"\n\nEnter The Name of The Student ";
//gets(name);
//cin.ignore();
cin>>name;
cout<<"\nEnter The admission no. ";
cin>>admno;
// getch();
}
void showdata()
{
cout<<"\nAdmission no. : "<<admno;
cout<<"\nStudent Name : "<<name<<endl;
//puts(name);
}
void display()
{
//student obj;
ifstream fp1;
fp1.open("student.dat",ios::binary);
while(fp1.read((char*)this,sizeof(*this)))
{
this->showdata();
fp1.read((char*)this,sizeof(*this));
}
fp1.close();
}
void add()
{
ofstream fp2;
fp2.open("student.dat",ios::binary|ios::app);
this->getdata();
fp2.write((char*)this,sizeof(*this));
fp2.close();
}
};
int main()
{
student obj;
//system("cls");
cout<<"\n1. Add new student";
cout<<"\n2. View all student";
cout<<"\n3. Search student";
cout<<"\n4. modify student";
cout<<"\n5. delete student";
cout<<"\n6. Exit";
cout<<"\n\nEnter your choice";
int ch;
cin>>ch;
switch(ch)
{
case 1:
obj.add();
break;
case 2:
obj.display();
//b.viewbook();
break;
default:
cout<<"Enter Valid choice";
}
return 0;
}
问题:
当我在文件中输入数据时,数据仅在备用步骤中写入文件。 在第一次运行并输入数据就可以了,在第二次运行中添加学生,数据不会写入文件中,并且在下一步中再次正确写入并继续在备用添加中提供正确的输出。
答案 0 :(得分:0)
您应该将switch
置于循环中:
bool exitLoop = false;
while(!exitLoop) {
int ch;
cin>>ch;
switch(ch) {
case '1':
obj.add();
break;
case '2':
obj.display();
//b.viewbook();
break;
case '6':
exitLoop = true;
break;
default:
cout<<"Enter Valid choice";
}
}
另请注意如何处理字符输入:1 != '1'