Reputation: 9380
I was trying out the below snippet but it is not giving the desired output:
#include<iostream>
#include<sstream>
using namespace std;
void MyPrint(ostream& stream)
{
cout<<stream.rdbuf()<< endl;
}
int main()
{
stringstream ss;
ss<<"hello there";
MyPrint(ss); //Prints fine
ostringstream oss;
oss<<"hello there";
MyPrint(oss); //Does not print anything
getchar();
}
I am aware that the only possible differences between stringstream
and ostringstream
is that the later forces the direction and is a bit faster than stringstream
.
Am I missing out on anything?
PS: A similar question was posted earlier but didn't get any answers.
Upvotes: 16
Views: 23481
Reputation: 4399
stringstream shouldn't be thought of as a bidirectional implementation of ostringstream and istringstream. It is implemented as a derrived class of both ostringstream and istringstream, which is why it implements both input and output capabilities.
Choosing which one to use depends on what it is used for. If you only need to write data to it on a stream without being able to access the data via a stream, then an ostringstream is all you would need. However, if you want to implement bidirectional on something you provide to an API but restrict it, you can cast it:
stringstream ss; // My bidirectional stream
ostringstream *p_os = &ss; // Now an output stream to be passed to something only allowed to write to it.
int bytes = collectSomeData(p_oss);
Upvotes: 1
Reputation: 153977
std::stringstream
and std::ostringstream
pass different
flags to the std::stringbuf
. In particular, the
std::stringbuf
of an std::ostringstream
does not support
reading. And std::cout << stream.rdbuf()
is a read operation
on the streambuf.
The way to extract characters from an std::ostringstream
is by
using the std::ostringstream::str()
function.
Upvotes: 25