为什么我的程序不从文件中读取数据

why my program does not read the data from file

本文关键字:读取 数据 文件 我的 程序 为什么      更新时间:2023-10-16

当我按"2"读取文件时,文件中的数据无法读取,尽管我的语法是正确的。为什么我的程序不能读取数据?顺序访问文件和随机访问文件的区别是什么?为什么首选随机访问文件?

void EnterRecord();
void ShowRecord();
using namespace std;
class student
{
    int rollno;
    string name;
    int marks;
    public:
        void SetData();
        void DisplayData();
        void MainMenu();
};
   void student:: MainMenu()
   {
      cout<<"                             "<<endl;
      cout<<"press 1 to enter record"<<endl;
      cout<<"press 2 to show record"<<endl;
   }
   void student::SetData()
   {
      cout<<"enter roll no of student"<<endl;
      cin>>rollno;
      cout<<"enter name of student"<<endl;
      cin>>name;
      cout<<"enter marks of student"<<endl;
      cin>>marks;
   }
   void student::DisplayData()
   {
      cout<<rollno<<setw(10)<<setw(10)<<marks<<endl;
   }
     int main()
     {
            student s1;
        int choice;
        repeat:
        s1.MainMenu();
        cout<<"enter ur choice ::"<<endl;
        cin>>choice;
        switch(choice)
        {
            case 1:
                EnterRecord();
                break;
                case 2:
                    ShowRecord();
                    break;
         }
           return 0;
     }
      void  EnterRecord()
   {
      ofstream myfile;
      myfile.open("student3.txt",ios::app);
      int choice=1;
      while(choice==1)
      {
        student s1;
          s1.SetData();
          myfile.write((char*)&s1,sizeof(student));
          cout<<"press 1 to enter record again"<<endl;
          cin>>choice;
          if(choice!=1)
          {
            system("cls");
           s1.MainMenu();
      }
         }
           myfile.close();
   }
     void ShowRecord()
     {
        student s2;
         ifstream myfile;
         myfile.open("student3.txt");
         myfile.seekg(0);
         while(myfile.eof())
         {
            myfile.read((char*)&s2,sizeof(student));
          }
          s2.DisplayData();
     }

最大的问题是,您将student的实例视为单个纯旧数据块(POD),而实际上它不是。它包含一个std::string的实例,其中包含您不知道的内部数据。第一个也是最明显的是,它包含一个指向字符串数据的指针。当你把它写出来时,你保存的是指针值而不是实际的字符串。当你重新加载它时,它会读取旧的指针值,这个值只有在你是一个非常幸运的小妖精时才有效。

您的函数EnterRecordShowRecord将需要更新,以便它们序列化student的每个成员,而不是将其作为单个blob的普通旧数据写出来。下面的内容应该可以让你开始。

保存数据:

myfile << st.rollno;
myfile << st.name;
myfile << st.marks;

加载数据
myfile >> st.rollno;
myfile >> st.name;
myfile >> st.marks;

既然你没有提供任何关于文件应该如何布局的信息,那么就由你来决定如何布局。传统上你会超载operator>>operator<<,但由于这看起来像家庭作业,这可能有点多。

你的代码还有其他几个问题…

  1. 您的case表达式不正确。您使用的 1和2与12键的ASCII值不同。你应该使用'1'和'2',而不是简单的1和2。

  2. 您还应该开始检查您调用的函数(如open)返回的错误。

  3. 检查eof在你的while循环是绝对不会工作的。参见Q&A @为什么循环条件中的iostream::eof被认为是错误的?

应该是:

switch(choice)
{
    case '1':
        EnterRecord();
        break;
    case '2':
        ShowRecord();
        break;
}