title: c++ read and write struct array with std::string into binary file
body: <p>I'm very new to c++ (and the question is a part of my homework).</p>
  <p>I need to store an array of structs in a binary file and read them back. The problem is that my struct contains <code>std::string</code> field. On the other side I can read the string, but nothing after it. Here is my structure definition:</p>
  <pre><code>struct Organization {
      int id;
      string name;
      float paidTaxes;
  };
  </code></pre>
  <p>and here is the code where I write array of this struct to a file:</p>
  <pre><code>void writeToFile(Organization *orgs, int n) {
      ofstream file(&quot;orgs.bin&quot;, ios::out | ios::binary);
      if (!file) { return; }
      for (int i = 0; i &lt; n; i++) {
          // determine the size of the string
          string::size_type sz = orgs[i].name.size();
          file.write(reinterpret_cast&lt;char*&gt;(&amp;orgs[i].id), sizeof(int));
          // write string size
          file.write(reinterpret_cast&lt;char*&gt;(&amp;sz), sizeof(string::size_type));
          // and actual string
          file.write(orgs[i].name.data(), sizeof(sz));
          file.write(reinterpret_cast&lt;char*&gt;(&amp;orgs[i].paidTaxes), sizeof(float));
      }
      file.close();
  }
  </code></pre>
  <p>and here is the code part where I'm reading this file back:</p>
  <pre><code>count = 0;
  Organization org;
  ifstream file;
  file.open(&quot;orgs.bin&quot;, ios::binary);
  while (file.good()) {
      string::size_type sz;
      file.read(reinterpret_cast&lt;char*&gt;(&amp;org.id), sizeof(int));
      file.read(reinterpret_cast&lt;char*&gt;(&amp;sz), sizeof(string::size_type));
      org.name.resize(sz);
      file.read(&amp;org.name[0], sz);
      file.read(reinterpret_cast&lt;char*&gt;(&amp;org.paidTaxes), sizeof(float));
      count++;
  }
  </code></pre>
  <p>As far as I understand, I need to run this loop to determine how many structs are stored in a file. When I run debugger, I successfully read <code>id</code> field, string size and actual string. However, I never get proper <code>paidTaxes</code> field (type of <code>float</code>) and subsequent loops return me junk.</p>
  <p>thanks in advance!</p>