-1

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?

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • You mean passing them through unchanged without effect on anything else? What's the definition of `getCode`? – Deduplicator Sep 23 '14 at 13:17
  • Does your function returns int or char? Please share the getCode prototype with us. – Sergei Lodyagin Sep 23 '14 at 13:18
  • Is getCode a struct with output stream operator? Maybe you are interested in setting and restoring iostream flags: http://stackoverflow.com/questions/4217704/roll-back-or-undo-any-manipulators-applied-to-a-stream-without-knowing-what-th – Sven Sep 23 '14 at 13:32
  • @Sven: Better a function which returns a streamable `struct`. – Deduplicator Sep 23 '14 at 13:43
  • I suspect you mean **ANSI** color codes? ASCII doesn't define colors. – MSalters Sep 23 '14 at 14:20

1 Answers1

4

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;
    }
};
James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • I suspect it returns `"\x1B[41m"`. I agree that your idea is better, you'd be able to just write `cout << Color::Red << "red text";` – MSalters Sep 23 '14 at 14:24
  • Thank you so much! It was so simple. I was already testing an implementation of a cache stream that sorted formatting strings and color codes... turns out you just need a simple wrapper class! – Vittorio Romeo Sep 23 '14 at 14:58