Reading directly from an std::istream into an std::string

c++, iostream, stdstring

Solution

`std::string` has a `resize` function you could use, or a constructor that'll do the same:

boost::uint16_t len;
is.read((char*)&len, 2);

std::string str(len, '\0');
is.read(&str[0], len);

This is untested, and I don't know if strings are mandated to have contiguous storage.

Problem

Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so? eg currently I can do it by ``` boost::uint16_t len; is.read((char*)&len, 2); char *tmpStr = new char[len]; is.read(tmpStr, len); std::string str(tmpStr, len); delete[] tmpStr; ```

Original source

Related problems