How to deal with unterminated character arrays when building C++ strings?
<p>As noted in <a href="http://stackoverflow.com/questions/5847480/what-is-the-c-idiom-to-replace-snprintf3">What is the C++ idiom to replace snprintf(3)?</a>, I'm parsing a file header and building an error message if a certain four-byte field in the header is corrupt. This code sums up what I'm trying to do:</p>

<pre><code>const std::string parseCapturePattern(const int fd) { // fd is the descriptor of the ogg file
  const char CAPTURE_PATTERN[4] = {'O', 'g', 'g', 'S'};
  char capture_pattern[4];

  read(fd, capture_pattern, sizeof(capture_pattern)); // error handling omitted
  if (strncmp(capture_pattern, CAPTURE_PATTERN, sizeof(capture_pattern)) != 0) {
    std::ostringstream err;
    /*** This won't actually work ***/
    err_msg &lt;&lt; "Invalid capture pattern: '" &lt;&lt; capture_pattern &lt;&lt; "'; expecting '"
        &lt;&lt; CAPTURE_PATTERN &lt;&lt; "'";
    /*** This won't actually work ***/

    return err.str();
  }
}
</code></pre>

<p>This will not work because <code>capture_pattern</code> and <code>CAPTURE_PATTERN</code> are not NULL-terminated character arrays. What does work is this:</p>

<pre><code>    err_msg &lt;&lt; "Invalid capture pattern: '" &lt;&lt; capture_pattern[0] &lt;&lt; capture_pattern[1] 
        &lt;&lt; capture_pattern[2] &lt;&lt; capture_pattern[3] &lt;&lt; "'; expecting '"
        &lt;&lt; CAPTURE_PATTERN[0] &lt;&lt; CAPTURE_PATTERN[1] &lt;&lt; CAPTURE_PATTERN[2]
        &lt;&lt; CAPTURE_PATTERN[3] &lt;&lt; "'";
</code></pre>

<p>That, of course, is almost indescribably hideous.</p>

<p>Any ideas?</p>
