Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if `cout` outputs to a terminal which accepts colors properly?

Is there another way than isatty to know if cout outputs to a terminal which accepts colors properly?

I'm using this header for colors, and I'm already using if(isatty(1)) to know if the output goes to a terminal.

Unfortunately when I output colors to Xcode's console I get unescaped sequences - but it works fine when executing the app itself from Terminal.app or iTerm in OS X.

I suppose that Xcode's console identifies itself as a terminal but still ignores color sequences...

So I'd like to have a better detection - if possible.

My code itself is trivial, something like this, returning a colored string if isatty is true, then it goes to cout:

std::string Slot::description()
{
    if(isatty(1))
    {
        return FBLU("my_string");
    }
    else
    {
        return "my_string";
    }
}

Xcode's output:

enter image description here

iTerm's output:

enter image description here

like image 434
Eric Aya Avatar asked Sep 01 '16 15:09

Eric Aya


Video Answer


1 Answers

For XCode specifically, you can check getenv("TERM"), as that will return null inside XCode and shouldn't do that if you're running in a "real" terminal.

For a more reliable way to determine whether you have a colour terminal, ncurses is probably the way to go.

like image 76
molbdnilo Avatar answered Oct 12 '22 10:10

molbdnilo