When I have:
std::ostringstream oss("Hello");
Why does this work:
std::cout << oss.str();
but this doesn't print anything:
std::cout << oss.rdbuf();
Reading the definition of operator<<(std::ostream&, std::streambuf*)
say that it will print characters from the buffer. Does oss.rdbuf()
not contain anything?
The str function takes the data string as an argument and assigns this data to the stringstream object.
In C++03 you'll have to either pass the stringstream as a parameter by non-const reference or return just the resulting string ( ss. str() ), as you can't copy the stream. Show activity on this post. You have to include sstream and have std::stringstream instead of stringstream .
Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
This issue is related to the fact that here, oss
is ostringstream object (ostringstream is output stream so its destination is to write to it and not to read from it) and to fact how streams manage its internal buffer.
You can change
std::ostringstream oss("Hello");
to
std::istringstream oss("Hello"); // or std::stringstream oss("Hello");
and it will work as expected. Alternatively use
std::cout << oss.rdbuf()->str(); // this will print a copy of all 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"
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With