如何在c ++中将包含指针变量的对象写入和读取到文件中?请使用以下代码帮助我

How to write and read an object which contains pointer variables into a file in c++?Help me with the following code

#include<iostream.h>
#include<conio.h>
#include<fstream.h>

struct node     /*node for info along with pointer variable*/
{
   char name[20];
   int n;
   node *next;
};

class info
{
   node *head,*tail;
   public:
   info();
   void insert();
   void display();
};

info::info()
{
   head=NULL;
   tail=NULL;
}

void info::insert()
{
   node *New;
   New=new node;
   cout<<"\nEnter the name and integer:";
   cin>>New->name>>New->n;
   New->next=NULL;
   if(head==NULL)
      head=tail=New;
   else
   {
      tail->next=New;
      tail=tail->next;
   }
}

void info::display()
{
   node *temp;
   temp=head;
   while(temp!=NULL)
   {
      cout<<"\nName:"<<temp->name<<" integer "<<temp->n;
      temp=temp->next;
   }
}

int main()
{
   info list1;
   clrscr();
   int ch;
   do
   {
      cout<<"\n1.insert 2.display 3.exit";
      cout<<"\nEnter choice:";
      cin>>ch;
      switch(ch)
      {
         case 1:
            cout<<"\nEnter the file name:";
            char *fn1;
            cin>>fn1;
            ofstream out(fn1,ios::binary);
            list1.insert();
            out.write((char *)&list1,sizeof(list1));
            out.close();
            break;
         case 2:
            cout<<"\nEnter the file name:";
            char *fn2;
            cin>>fn2;
            ifstream in(fn2,ios::binary);
            in.read((char*)&list1,sizeof(list1));
            list1.display();
            in.close();
            break;
      }
   }while(ch!=3);
   return 0;
}

在上面的代码中,我使用了“*head”和“*tail”指针变量来构建队列。问题是如何将信息写入文件并读取 文件中的信息? 代码 运行 它没有 运行 正确。

有些东西可以帮助你。

保存和恢复一个对象

node n1;
strcpy(n1.name, "Sai Charan");
n1.n = 10;

想一想您需要保存到文件中的内容,以便能够将文件中的数据恢复到另一个文件中 node

保存并恢复 vector<node>

std::vector<node> nodes;

// Add couple of node objects to node.

想一想您需要保存到文件中的内容,以便能够将文件中的数据恢复到另一个文件中 vector<node>

现在将相同的逻辑应用于info

这应该为您提供足够的背景知识,以便能够在 info 对象中保存和恢复 node 的链表。