Is there a way to print colored output using iostream
and Xcode? I\'d like to be able to, for example, print Hello World!
with Hello
red,
In a more c++ way for an ANSI capable terminal, it is possible to write your own ansi stream manipulators like std::endl but for handling ansi escape code.
Code for doing so can look like this for basic raw implementation:
namespace ansi {
template < class CharT, class Traits >
constexpr
std::basic_ostream< CharT, Traits > & reset( std::basic_ostream< CharT, Traits > &os )
{
return os << "\033[0m";
}
template < class CharT, class Traits >
constexpr
std::basic_ostream< CharT, Traits > & foreground_black( std::basic_ostream< CharT, Traits > &os )
{
return os << "\033[30m";
}
template < class CharT, class Traits >
constexpr
std::basic_ostream< CharT, Traits > & foreground_red( std::basic_ostream< CharT, Traits > &os )
{
return os << "\033[31m";
}
...
} // ansi
And it can be used in a code like this:
std::cout << ansi::foreground_red << "in red" << ansi::reset << std::endl;