2

I specifically need to convert an ostream into a string. To be more precise, I have a function:

ostream& f(ostream& out); 

(This function is mainly used for a polymorphic overcharge of the << operator) In this case, I need to get what is in the ostream into the string. After some research, I tried this:

stringstream test;
ofstream tmp;
test << f(tmp);
string foo(test.str());

But the string only contains 0s. Does anyone have a solution for this ?

Thank you

Raiv
  • 5,731
  • 1
  • 33
  • 51
  • I don't understand what you mean by "what is in the ostream" - an ostream is an abstraction of an output stream - do you mean what is in its buffer at a given point?. –  May 27 '11 at 14:37

1 Answers1

0

Try to use ostringstream class instead of ofstream

ostringstream test;
test << f(test);
string foo(test.str());
Raiv
  • 5,731
  • 1
  • 33
  • 51
  • Thank you very much that was quick and on point; There is a continuation question: how does the order work? – Simon Löwe May 27 '11 at 14:58
  • Which order? Do you mean order of statement executions? – Raiv May 27 '11 at 15:00
  • I mean: if you write : test << string << f(test) or test << f(test) << string; it gives the same thing is that normal ? – Simon Löwe May 27 '11 at 15:04
  • this depends on what your function f(test) do. if it writes to stream, then it executes first, modifies the stream, and after that a string being copied to that stream. i suggest you can even write simply f(test)< – Raiv May 27 '11 at 15:21