How can I copy an ostringstream object into another one (using gcc-4.7.0)

218 views Asked by At

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

1

There are 1 answers

0
Captain Obvlious On

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
}