Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefixes to ostream outputs

I am looking for a way of adding a prefix to an ostream, pass it down to other functions so that their outputs are prefixed and then remove it to continue.

Check the following pseudocode:

...
void function(ostream &out){
    out << "output 1\n";
    out << "output 2\n";
}

cout << "Whatever\n";
add_suffix(cout,"function: ");
function(cout);
remove_suffix(cout);
...

With an output like:

...
Whatever
function: output 1
function: output 2
...

Looking at the docs of ostream they state that sentry might be used for prefixing/suffixing but i don't know how to do this if the intended use is what I want.

The ostream::sentry documentation says:

sentry: Perform exception safe prefix/suffix operations
like image 438
Arkaitz Jimenez Avatar asked Dec 01 '25 05:12

Arkaitz Jimenez


1 Answers

The general way goes like this: Define YourStreamBuffer that is a streambuf that inserts your prefix after any newline that is written to it, and sends the output to a destination buffer. Then use it like this:

streambuf *oldBuf = cout.rdbuf();

YourStreamBuffer yourBuf(oldBuf, "function: ");
// everything written to yourBuf is sent to oldBuf

cout.rdbuf(&yourBuf);
function(cout);
cout.rdbuf(oldBuf);

You can find plenty examples on the net on how to implement your stream buffers. Also make sure that your code is exception safe, that is restore oldBuf even if an exception is thrown.

Note: sentries are something different, it's not what you need here.

like image 82
Yakov Galka Avatar answered Dec 03 '25 19:12

Yakov Galka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!