title: How to read from file and store in array of objects in c++
body: <p>I am learning c++ and have a trouble in file handling. I am writing a code as a homework where i have to write objects into a file and then read those objects as array from the file at once. Here is my code:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  class Records{
      char* name;
      int roll;
  public:
      Records()
      {
          name = new char[20];
      }
      void setData()
      {
          cout&lt;&lt;&quot;Enter name: &quot;&lt;&lt;endl;
          cin&gt;&gt;name;
          cout&lt;&lt;&quot;Enter roll&quot;&lt;&lt;endl;
          cin&gt;&gt;roll;
      }
      char* getname()
      {
          return name;
      }
      int getRoll()
      {
          return roll;
      }
      void operator = (Records&amp; no)
      {
          name = no.name;
          roll = no.roll;
      }
  };
  
  int main()
  {
      int i =0 ;
      Records rec;
      rec.setData();
      Records::increase();
      ofstream fout;
      fout.open(&quot;file.txt&quot;, ios::app);
      fout.write((char*)&amp;rec, sizeof(rec));
      fout.close();
  
      Records* results = new Records[20];
      Records rec1;
      ifstream fin;
      fin.open(&quot;file.txt&quot;, ios::in);
      while(!fin.eof())
      {
          fin.read((char*)&amp;rec1, sizeof(rec1));
          results[i] = rec1;
          i++;
      }
      fin.close();
      cout&lt;&lt;results[0].getRoll();
      return 0;
  }
  </code></pre>
  <p>So basically, I made a Records class and store its object in a file. That works fine but I faced problem while taking data from file. It is not showing anything or sometimes showing garbage value. Anyone have better idea please hep me.
  Thanks in advance!</p>