Search code examples
c++string-formattingcrt

Formatted text output to std::string object using std::ostream methods


I've made a function dump_text(std::ostream &) that dumps some text in a standard output stream. The text goes to a file or to the user console. Now, I want that text to end up in a standard string object (see the next code sample).

void dump_text(std::ostream &p_ostream)
{
    p_ostream << "text that must endup in string object";
}

class my_class
{
    public:
    my_class(std::string &);
    operator std::ostream & ();
};

int main(int, char **)
{
    std::string l;
    my_class k(l);

    dump_text(k);
}

1) Is there a standard implementation of 'my_class' in the CRT-library? 2) Does anyone know a better solution to this problem of assigning text to a string using std::ostream - methods?


Solution

  • You would use a std::ostringstream.

    #include <sstream>
    using namespace std;
    
    ...
    ostringstream out;
    dump_text(out);
    string value = out.str();
    ...