send outpot to char buffer instead of &cout

I have lots of code like this ...
(*output equals &cout)

*output << "none (";
*output << target->getName();
*output << ")\n";

is there a simple way using "find and replace"
to put the data into a char array instead of
cout ?
Last edited on
You can use a stringstream which will put the data in a string.

From that string you can get a char array if you really want (or you could just use the string):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <string>
#include <sstream>
#include <iostream>

void outputfunc(std::ostream* output)
{
    // a function that prints stuff to the given ostream 'output'
    *output << "example";
    *output << "example";
    *output << "example";
}


int main()
{
    // print some stuff to cout:
    outputfunc( &std::cout );

    // print some stuff to a string:
    std::stringstream ss;
    outputfunc( &ss );

    std::string str = ss.str();
       // here, 'str' is a string containing "exampleexampleexample"
}
> is there a simple way using "find and replace"
> to put the data into a char array instead of cout ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <sstream>

int main()
{
    // right at the beginning

    // http://www.cplusplus.com/reference/sstream/stringbuf/stringbuf/
    std::stringbuf sbuf( std::ios_base::out ) ;
    // http://www.cplusplus.com/reference/ios/ios/rdbuf/
    const auto old_buf = std::cout.rdbuf(&sbuf) ;

    // in the rest of the program, use cout as it is being used right now

    std::cout << "hello world " << 12345 << ' ' << '$' ; // for example

    // finally, at the end

    std::cout.rdbuf(old_buf) ;
    // http://www.cplusplus.com/reference/sstream/stringbuf/str/
    const std::string text_out = sbuf.str() ;
    std::cout << "string text_out contains: " << text_out << '\n' ;
}

http://coliru.stacked-crooked.com/a/d0c8aaf49f1a6b05
Thank you for the responses.
I used this code ...
1
2
std::stringstream ss;
    outputfunc( &ss );
successfully BUT. on the
second call to ...
1
2
3
4
outputfunc( &ss );

std::string str = ss.str();
PCSTR pszBuffer = &str[0];
I get ...
exampleexampleexampleexampleexampleexample
How can I clear ss ?
How can I clear ss ?
ss.str("");
Topic archived. No new replies allowed.