简体   繁体   中英

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?

You would use a std::ostringstream .

#include <sstream>
using namespace std;

...
ostringstream out;
dump_text(out);
string value = out.str();
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM