Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference stringstream and ostringstream

Tags:

c++

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.

like image 826
Saksham Avatar asked Aug 15 '13 11:08

Saksham


People also ask

What is the difference between Stringstream and Istringstream?

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.

What is Ostringstream used for?

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.

What does Ostringstream mean in C++?

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 .

Is Stringstream fast?

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!


1 Answers

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.

like image 93
James Kanze Avatar answered Sep 27 '22 18:09

James Kanze