Search code examples
c++c++11consoleiostreammanipulators

Dealing with iostream manipulators and ANSI console color codes


I'm using ANSI color codes to format my output in an Unix console.

const auto& getCode(Color mColor) 
{
    static std::map<Color, std::string> codes;
    // ...
    return codes[mColor]
}

cout << getCode(Color::Red) << "red text";

When using manipulators such as std::setw or std::left, however, the results are affected by the color code, as it is a bunch of characters.

How should I deal with this issue? Is there a way to make stream manipulators ignore color codes?


Solution

  • What is the type returned by getCode? If it isn't std::string or char const*, all you need to do is write a << for it which ignores the formatting data you don't want to affect it. If it's one of C++'s string types, then you should probably wrap the call in a special object, with an << for that object type, e.g.:

    class ColorCode
    {
        ColorType myColor;
    public:
        ColorCode(ColorType color) : myColor( color ) {}
        friend std::ostream& operator<<( std::ostream& dest, ColorCode const& cc )
        {
            std::string escapeSequence = getCode( myColor );
            for ( char ch : escapeSequence ) {
                dest.put( ch );
            }
            return dest;
        }
    };