仅在交替步骤中写入文件中的数据

data written in file only in alternate steps

本文关键字:数据 文件      更新时间:2023-10-16

代码

#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<<"nnEnter 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<<"nnEnter 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;
}

问题:

当我在文件中输入数据时,数据只在交替的步骤中写入文件。在第一次运行并输入数据时,它是可以的,在第二次运行以添加学生时,数据没有写入文件中,在下一步中,它再次正确写入,并在交替添加中继续提供正确的输出。

您应该将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'