Here's a version of the code above from @nightcracker, using stringstream
instead of itoa
. (This runs using clang++, C++11, OS X 10.7, iTerm2, bash)
#include
#include
#include
enum Color
{
NONE = 0,
BLACK, RED, GREEN,
YELLOW, BLUE, MAGENTA,
CYAN, WHITE
};
static std::string set_color(Color foreground = NONE, Color background = NONE)
{
std::stringstream s;
s << "\033[";
if (!foreground && ! background){
s << "0"; // reset colors if no params
}
if (foreground) {
s << 29 + foreground;
if (background) s << ";";
}
if (background) {
s << 39 + background;
}
s << "m";
return s.str();
}
int main(int agrc, char* argv[])
{
std::cout << "These words should be colored [ " <<
set_color(RED) << "red " <<
set_color(GREEN) << "green " <<
set_color(BLUE) << "blue" <<
set_color() << " ]" <<
std::endl;
return EXIT_SUCCESS;
}