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.
A stringstream is an iostream object that uses a std::string as a backing store. An ostringstream writes to a std::string . An istringstream reads from a std::string . You read & write from & to an istringstream or ostringstream using << and >> , just like any other iostream object.
Stringstream class is used for insertion and extraction of data to/from the string objects. It acts as a stream for the string object. The stringstream class is similar to cin and cout streams except that it doesn't have an input-output channel.
std::ostringstreamOutput stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str .
stringstreams are primarily there for convenience and type-safety, not speed. The stream will collect the input and then eventually call strtold for the conversion. Makes it hard to be any faster!
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.
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