title: copying from a std::string to a char array and null-terminating the result
body: <p>I have a Visual Studio 2008 C++03 application where I want to copy from a std::string to a char array, but I need the char array to be null terminated even if it must truncate the string to do so. </p>
  
  <p>This, for instance works as desired:</p>
  
  <pre><code>inline void CopyAndNullTerminate( const std::string&amp; source, 
                                    char* dest, 
                                    size_t dest_size )
  {
      source.copy( dest, dest_size );
      using std::min;
      char* end = dest + min( dest_size - 1, source.size() );
      *end = '\0';
  }
  
  int main()
  {
      enum{ MAX_STRING_SIZE = 15 };
      char dest[ MAX_STRING_SIZE ];
      std::string test = "This is a test";
  
      CopyAndNullTerminate( test, dest, MAX_STRING_SIZE );
  
      assert( strcmp( test.c_str(), dest ) == 0 );
      return 0;
  }
  </code></pre>
  
  <p>example: <a href="http://ideone.com/0EBYb" rel="noreferrer">http://ideone.com/0EBYb</a></p>
  
  <p>Is there a shorter, more efficient method of doing this?</p>
  
  <p>Thanks</p>