Copy a streambuf’s contents to a string

I don’t know whether it counts as “excessive copying“, but you can use a stringstream:

std::ostringstream ss;
ss << someStreamBuf;
std::string s = ss.str();

Like, to read everything from stdin into a string, do

std::ostringstream ss;
ss << std::cin.rdbuf();
std::string s = ss.str();

Alternatively, you may also use a istreambuf_iterator. You will have to measure whether this or the above way is faster – i don’t know.

std::string s((istreambuf_iterator<char>(someStreamBuf)), 

Note that someStreamBuf above is meant to represent a streambuf*, so take its address as appropriate. Also note the additional parentheses around the first argument in the last example, so that it doesn’t interpret it as a function declaration returning a string and taking an iterator and another function pointer (“most vexing parse”).

Leave a Comment