0

[SOLUTION]

You can pass a stringstream into the paramater that takes an ostream. After that you can get the text that was set inside the stringstream by its str() funktion.

#include <sstream> ... { stringstream ss; print(ss); string text; text = ss.str(); // Handle text } 

Given there's a function like this:

void print(ostream& stream) const; 

How can I access the data that is written into the ostream?

I was thinking of interpreting it as a string:

string text; print( text ); // Interpret text 

The reason is there's another function that has a pointer to an object as a parameter:

void append( *Data data ); 

And I must use the data objects print method to get at its data:

// This is a public function in the Data class void append( *Data data ) { string text; data->print( text ); // append data to this Data object } 

I was trying to cast to a stringstream but that didn't work. I'm thinking if I could save the data to a file and then read it as workaround.

1 Answer 1

3

Instead of this...

string text; print( text ); 

...try this...

ostringstream text; print( text ); 

Then you can use the text written into "text".

Sign up to request clarification or add additional context in comments.

4 Comments

Hmm, it doesn't spit any error but how can I convert the ostringstream to a string? the << operator doesn't work. neither does the ostringstreams str member and niether any combination of get or getline().
@user1356190: how were you trying to use the str() member function? Will work ala std::cout << text.str() << '\n';
Oh I didn't realize it had a str() function! Looking at the link [link]cplusplus.com/reference/iostream/ostream it doesn't say anywhere. Anyway, I passed a stringstream as the paramater for ostream and then I converted it into a string with "text = ss.str()". It works perfectly, thank you!
@user1356190: You're welcome. BTW - ostream is the base class - modelling any output stream, many of which don't keep a record of their output as it's sent to a network or device and no longer needed locally. ostream doesn't have a str() member function. The derived class ostringstream adds one though - it exists precisely to let you capture stream output in a string. Because print() accepts an ostream by reference, any derived class can be passed in and work polymorphically.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.