I edited the original code to fix the bug.
We have to manually check for eof. Using eof as loop control is a bad idea™ (the faq on the site explain why). Furthermore, what happens if we hit end of file just after reading the length? Another thing not covered by your code.
Although, std::string is not guaranteed to be contiguous, that is of no concern since we're storing a C-style string which is guaranteed to be contiguous and nul-terminated. Similarly, when we read back, it will construct a new string from the C-style string.