Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out a stringstream using str() and rdbuf()

Tags:

c++

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?

like image 481
template boy Avatar asked Oct 12 '14 21:10

template boy


People also ask

What does str () do in C++?

The str function takes the data string as an argument and assigns this data to the stringstream object.

How do I return a Stringstream in C++?

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 .

What is the difference between string and 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.

Is Stringstream a string?

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.


1 Answers

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;
}
like image 86
4pie0 Avatar answered Oct 11 '22 09:10

4pie0