Here is a simple piece of code what should print a std::ostringstream
buffer, which in turn has been obtained via rdbuf()
. I expect that this buffer to be printed to std::cout
either via istreambuf
iterators or directly via <<
operator. Surprisingly nothing can print this buffer. The more interesting that <<
operator clears this buffer out.
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
std::ostringstream buf_ref;
buf_ref << "bgdgdgdfg" << std::endl;
auto buff = buf_ref.rdbuf();
std::cout << "1 " << buf_ref.str() << std::endl;
std::copy(std::istreambuf_iterator<char>(buff), std::istreambuf_iterator<char>(), std::ostream_iterator<char>(std::cout));
std::cout << "2 " << buf_ref.str() << std::endl;
std::cout << buff << std::endl; /*Why it clears the buffer? Why it doesn't output anything?*/
std::cout << "3 " << buf_ref.str() << std::endl;
return 0;
}
Any ideas what is wrong here? BTS, Here is the reference which describes that << operator is overloaded for a streambuf* cplusplus.com/reference/ostream/ostream/operator%3C%3C So it should be a content of the streambuf to be printed.