c++ - Printing out a stringstream using str() and rdbuf() -
when have:
std::ostringstream oss("hello");
why work:
std::cout << oss.str();
but doesn't print anything:
std::cout << oss.rdbuf();
reading definition of operator<<(std::ostream&, std::streambuf*)
print characters buffer. oss.rdbuf()
not contain anything?
this issue related fact here, oss
ostringstream object (ostringstream output stream destination write it , not read it) , fact how streams manage internal buffer.
you can alter
std::ostringstream oss("hello");
to
std::istringstream oss("hello"); // or std::stringstream oss("hello");
and work expected. alternatively use
std::cout << oss.rdbuf()->str(); // print re-create of buffer content
example:
#include <iostream> #include <sstream> int main() { std::ostringstream oss("hello"); std::istringstream oss2("hello"); cout << oss.rdbuf()->str() << endl; // prints "hello" cout << oss2.rdbuf(); // prints "hello" homecoming 0; }
c++
No comments:
Post a Comment