c++c++17outputoutputstreamansi-escape

How to color the output stream of std::cout, but not of std::cerr and std::clog?


I am dealing with the following problem: I am on Ubuntu and if I color all the stream in red, for example with the following command:

#include <iostream>

std::cout << "\033[31m" << "From now on the stream is red!";

what happens is that not only the std::cout object, but also std::cerr and std::clog objects will display red strings from now on.

I was wondering if is there a way to color only std::cout output and let std::cerr and std::clog outputs unchanged, in a way to be able to do:

#include <iostream>

std::cout << "\033[31m" << "From now on the std::cout stream is red!"; // red stream
std::cerr << "This stream is NOT red"; // normal stream (not colored)
std::clog << "This stream is NOT red"; // normal stream (not colored)

What I need is a "setting" (function, class etc...) able to fix this requirement at the beginning of the program and let it unchanged until the end.

How can I do this?


Solution

  • After a few days of tries I found a pretty suitable solution for this problem. I simply created a functor able to apply changes directly to the std::ostream object, to be used in this way:

    functor( std::cout ) << "Modified output stream";
    

    Such an implementation si a bit long and can be found here.