使用类处理文件时出错?

时间:2013-12-19 06:08:33

标签: c++ class file-handling

代码如下:

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();

}

该计划即将使用课程读写学生的详细信息。

错误

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

找到

输出

nitin,rollno 12有98%的分数。 nitin,rollno 12有98%的分数。

预期输出

nitin,rollno 12有98%的分数。

1 个答案:

答案 0 :(得分:0)

试试这个:

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();

}