使用类处理文件时出错

Error in file handling using classes?

本文关键字:出错 文件 处理      更新时间:2023-10-16

代码是这样的:

class student 
    {
      char name[20];
      int roll;
      float marks;
   public:
    void getdata(void)
     {
        char ch;
        cin.get(ch);
        cout << "Name : ";
        cin.getline(name, 20);
        cout << "nRoll no : ";
        cin >> roll;
        cout << "nMarks : ";
        cin >> marks;
        cout << "n";
     }
  void display(void)
    {
         cout << "n" << name << " ,roll no " << roll << " has " << marks
         << "% marks.n";
    }
  int getroll()
    { return roll; }
 };
void main() 
{
   clrscr();
   student s1;
   fstream fil;
   int rn;
   char ans = 'y';
   fil.open("stu.dat", ios::out);
    while (ans == 'y')
     {
        s1.getdata();
        fil.write((char *)&s1, sizeof(s1));
        cout << "n Do you want to enter more records :?";
        cin >> ans;
      }
     fil.close();
     fil.open("stu.dat", ios::in);
      fil.seekg(0);
      while (fil) 
       {
          fil.read((char *)&s1, sizeof(s1));
          s1.display();
       }
      fil.close();
     getch();
}

该程序即将使用类读取和写入学生的详细信息。

错误

如果我输入一次详细信息,输出会显示两次详细信息。

找到的输出

尼廷,罗尔诺 12 有 98% 的分数。尼廷,罗尔诺 12 有 98% 的分数。

预期输出

尼廷,罗尔诺 12 有 98% 的分数。

试试这个:

class student 
    {
      char name[20];
      int roll;
      float marks;
   public:
    void getdata(void)
     {
        char ch;
        cin.get(ch);
        cout << "Name : ";
        cin.getline(name, 20);
        cout << "nRoll no : ";
        cin >> roll;
        cout << "nMarks : ";
        cin >> marks;
        cout << "n";
     }
  void display(void)
    {
         cout << "n" << name << " ,roll no " << roll << " has " << marks
         << "% marks.n";
    }
  int getroll()
    { return roll; }
 };
void main() 
{
   clrscr();
   student s1;
   fstream fil;
   int rn;
   char ans = 'y';
   fil.open("stu.dat", ios::out);
    while (ans == 'y')
     {
        s1.getdata();
        fil.write((char *)&s1, sizeof(s1));
        cout << "n Do you want to enter more records :?";
        cin >> ans;
      }
     fil.close();
     fil.open("stu.dat", ios::in);
      fil.seekg(0);
      while (fil) 
       {
          fil.read((char *)&s1, sizeof(s1));
          if (feof(fil)) {
              puts ("End-of-File reached.");
              break;
          }
          s1.display();
       }
      fil.close();
     getch();
}