【问题标题】:Error in file handling using classes?使用类处理文件时出错?
【发布时间】:2013-12-19 06:08:32
【问题描述】:

代码如下:

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% 的分数。

【问题讨论】:

  • 准备minimal complete example的能力是一项非常有用的技能。
  • 完成编辑。更正任何人??
  • 你检查文件“stu.dat”了吗?它包含两条记录还是只有一条?
  • 是的,我检查了“stu.dat”文件,它只包含一条记录。

标签: c++ class file-handling


【解决方案1】:

试试这个:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    相关资源
    最近更新 更多