-1

All the other posts tell me to change my compiler, but I can't since I'm supposed to be working with this compiler. Please help!

void foo(ostringstream &os) {
    ostringstream temp;
    temp << 0;
    //do something
    os.swap(temp);
}

^I can' really upload the do-something part, since it's a part of a school project, but the compiler is giving me an error at: os.swap(temp);

I also tried the =operator and that didn't work as well

soochism
  • 13
  • 1
  • 5
  • 2
    Hard to provide a solution without seeing exactly what you're trying to accomplish in your code. Please **edit** your post and include the _relevant_ portions of code there. – Captain Obvlious Dec 07 '14 at 04:01
  • The simple solution in the sample you posted would be to use `os` directly instead of a second `temp` stream that later has to get copied to `os`. – sth Dec 07 '14 at 14:41

1 Answers1

1

You can use the str member function in std::ostringstream to both obtain the buffer from the temporary stream and set the buffer passed to foo.

#include <iostream>
#include <string>
#include <sstream>

void foo(std::ostringstream &os)
{
    std::ostringstream temp;

    temp << "goodbye";

    //do something

    os.str(temp.str()); //  Set the new buffer contents
}


int main()
{
    std::ostringstream out;

    out << "hello";
    std::cout << out.str() << std::endl;
    foo(out);
    std::cout << out.str() << std::endl;
}

Alternatively you can eliminate the use of a temporary stream by clearing the buffer in os as soon as you enter foo and output directly to os. Your post doesn't provide enough information to determine if this will be useful to you but it's an option.

void foo(std::ostringstream &os)
{
    os.str(""); //  Set the new buffer contents

    os << "goodbye";

    // do something
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74