String streams

suggest change

std::ostringstream is a class whose objects look like an output stream (that is, you can write to them via operator<<), but actually store the writing results, and provide them in the form of a stream.

Consider the following short code:

#include <sstream>
#include <string>                                                                                                                          

using namespace std;

int main()
{
    ostringstream ss;
    ss << "the answer to everything is " << 42;
    const string result = ss.str(); 
}

The line

ostringstream ss;

creates such an object. This object is first manipulated like a regular stream:

ss << "the answer to everything is " << 42;

Following that, though, the resulting stream can be obtained like this:

const string result = ss.str();

(the string result will be equal to "the answer to everything is 42").

This is mainly useful when we have a class for which stream serialization has been defined, and for which we want a string form. For example, suppose we have some class

class foo 
{   
    // All sort of stuff here.
};  

ostream &operator<<(ostream &os, const foo &f);

To get the string representation of a foo object,

foo f;

we could use

ostringstream ss; 
ss << f;
const string result = ss.str();

Then result contains the string representation of the foo object.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Streams:
* String streams

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype