std::istreambuf_iterator<char> eos;std::string s(std::istreambuf_iterator<char>(stream), eos);
----------------------------------------------------------------------------
(Could is a one-liner if not for MVP)
post-2011 edit, this approach are now spelled
std::string s(std::istreambuf_iterator<char>(stream), {});
----------------------------------------------------------------------------
I ' m late to the party, but this is a fairly efficient solution:
Std::String Gulp(Std::IStream&Inch){Std::string ret; CharBuffer[4096]; While (Inch.Read (buffer, sizeofbuffer Ret. (buffer, sizeof buffer Ret.append (buffer, in gcount ()); return Ret; /span>
I did some benchmarking, and it turns out of that the std::istreambuf_iterator
technique (used by the accepted answer) is actually much slower. On GCC 4.4.5 -O3
with, it's about a 4.5x difference in my machine, and the gap becomes wider with lower optimization set Tings.
----------------------------------------------------------------------------
You can try using the something from algorithms. I have the to get ready for work but here's a very quick stab at things (there's got to be a better):
copy( istreambuf_iterator<char>(stream), istreambuf_iterator<char>(), back_inserter(s) );
----------------------------------------------------------------------------
You could do
std::string s;std::ostringstream os;os<<stream.rdbuf();s=os.str();
But I don ' t know if it's more efficient.
Alternative version:
std::; Std::ostringstream os;>>os.=os.
----------------------------------------------------------------------------
Well, the If you is looking for a simple and ' readable '-to-do it. I would recomend add/use some high level framework on your project. For that I's always use Poco and Boost in all my projects. In the case, with Poco:
string text; FileStream fstream(TEXT_FILE_PATH); StreamCopier::copyToString(fstream, text);
----------------------------------------------------------------------------
Perhaps this 1 line c++11 solution:
std::vector<char> s{std::istreambuf_iterator<char>{in},{}};
C + + istream conversion to std::string