The code goes like this:

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

}

The program is about to read and write details of a student using classes.

error

The output shows the details twice if i enter the details once.

output found

nitin, rollno 12 has 98% marks. nitin, rollno 12 has 98% marks.

output expected

nitin, rollno 12 has 98% marks.

有帮助吗?

解决方案

Try this :

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

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top