25

Is it possible to pass in a stringstream and have the function write to it directly?

I remember I saw a function invoked similar to something like this:

my_func(ss << "text" << hex << 33);
brad
  • 930
  • 9
  • 22
rsk82
  • 28,217
  • 50
  • 150
  • 240

4 Answers4

23

Sure thing. Why wouldn't it be? Example declaration of such function:

void my_func(std::ostringstream& ss);
eq-
  • 9,986
  • 36
  • 38
  • thank you, that what I missed, I knew it is somewhat possible but I didn't know what declaration use to achieve that effect – rsk82 May 31 '12 at 12:06
  • 4
    Except that the type of `ss << "test" << hex << 33` is not `std::stringstream&`, but `std::ostream&`, and that won't match the given signature. – James Kanze May 31 '12 at 14:34
  • @JamesKanze for some reason, compiler does not complain, see GDB online https://onlinegdb.com/2FgGiOBfHw – Welgriv Nov 25 '22 at 11:19
  • However, still wondering why not using `stringstream` instead of `ostream`... – Welgriv Nov 25 '22 at 11:21
12

Absolutely! Make sure that you pass it by reference, not by value.

void my_func(ostream& stream) {
    stream << "Hello!";
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

my_func has to have a signature along the lines of:

void my_func( std::ostream& s );

, since that's the type of ss << "text" << hex << 33. If the goal is to extract the generated string, you'ld have to do something like:

void
my_func( std::ostream& s )
{
    std::string data = dynamic_cast<std::ostringstream&>(s).str();
    //  ...
}

Note too that you can't use a temporary stream;

my_func( std::ostringstream() << "text" << hex << 33 );

won't compile (except maybe with VC++), since it's not legal C++. You could write something like:

my_func( std::ostringstream().flush() << "text" << hex << 33 );

if you wanted to use a temporary. But that's not very user friendly.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
1

Yes it is, and

Function(expresion)

Will make the expression to be evaluated first and the result of it will be passed as a parameter

Note: Operator << for ostreams returns a ostream

Mario Corchero
  • 5,257
  • 5
  • 33
  • 59