title: Reading binary data into std::string c++
body: <p>I am trying to read data from binary file to an std::string.Here is what I have tried at first.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  int main(int argc, char const *argv[])
  {
      fstream file("output.bin" , ios::out | ios::binary | ios::in);
      string my_str(5, '\0');
      file.read(my_str.c_str(), 5);
      cout &lt;&lt; "String = " &lt;&lt; my_str&lt;&lt; endl ;
  }
  </code></pre>
  
  <p>And the compiler gave the error :</p>
  
  <pre><code>error: invalid conversion from ‘const char*’ to ‘std::basic_istream&lt;char&gt;::char_type* {aka char*}’ [-fpermissive]
    file.read(my_str.c_str(), 5);
  </code></pre>
  
  <p>As far as I understand, c_str() returns a const pointer which cannot be used in read method, so I changed my approach a little bit(which you can see below). Is there a better way to do this ?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  int main(int argc, char const *argv[])
  {
      fstream file("output.bin" , ios::out | ios::binary | ios::in);
      string my_str(5, '\0');
      char buffer[6];
      file.read(buffer, 5);
      buffer[5] = '\0';
      my_str = string(buffer);
  
      cout &lt;&lt; "String = " &lt;&lt; my_str&lt;&lt; endl ;
  }
  </code></pre>
  
  <p>ps : forgive me if I could not make myself clear, this is my first time here :)</p>