Eric Aya Eric Aya - 3 months ago 30
C++ Question

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

Answer

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.