Arkaitz Jimenez Arkaitz Jimenez - 1 year ago 62
C++ Question

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: ");

With an output like:

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.

documentation says:

sentry: Perform exception safe prefix/suffix operations

Answer Source

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


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.