C++中的彩色输出

问题描述:

有没有使用iostream和Xcode打印彩色输出的方法?我希望能够,例如,打印Hello World!Hello红色,World蓝色和!黄色。我怎样才能做到这一点?C++中的彩色输出

+1

可能的重复(至少相关)http://stackoverflow.com/questions/7414983/how-to-use-the-ansi-escape-code-for-outputting-colored-text-on-console – 2012-02-06 09:40:30

+0

阅读这个线程http://www.daniweb.com/software-development/cpp/threads/9921 – 2012-02-06 09:40:34

+0

看到http://ascii-table.com/ansi-escape-sequences.php – 2012-02-06 09:47:09

您需要终端颜色代码。对于Linux的是以下(您的系统可能会有所不同,看起来它):

//the following are UBUNTU/LINUX ONLY terminal color codes. 
#define RESET "\033[0m" 
#define BLACK "\033[30m"  /* Black */ 
#define RED  "\033[31m"  /* Red */ 
#define GREEN "\033[32m"  /* Green */ 
#define YELLOW "\033[33m"  /* Yellow */ 
#define BLUE "\033[34m"  /* Blue */ 
#define MAGENTA "\033[35m"  /* Magenta */ 
#define CYAN "\033[36m"  /* Cyan */ 
#define WHITE "\033[37m"  /* White */ 
#define BOLDBLACK "\033[1m\033[30m"  /* Bold Black */ 
#define BOLDRED  "\033[1m\033[31m"  /* Bold Red */ 
#define BOLDGREEN "\033[1m\033[32m"  /* Bold Green */ 
#define BOLDYELLOW "\033[1m\033[33m"  /* Bold Yellow */ 
#define BOLDBLUE "\033[1m\033[34m"  /* Bold Blue */ 
#define BOLDMAGENTA "\033[1m\033[35m"  /* Bold Magenta */ 
#define BOLDCYAN "\033[1m\033[36m"  /* Bold Cyan */ 
#define BOLDWHITE "\033[1m\033[37m"  /* Bold White */ 

这可以让你做到以下几点:

std::cout << RED << "hello world" << RESET << std::endl; 

注意:如果你不使用复原色彩将保持更改,直到下次使用颜色代码。

+0

他在Mac OS上(至少我假设他是,因为他提到XCode),所以这应该工作。 – 2012-02-06 09:54:47

+8

它将在终端工作,但不在Xcode控制台窗口 – 2012-02-06 10:10:26

+0

@ shuttle87,感谢您的回复。我怎样才能用3种不同的颜色设置3个变量,比如'char hello ='H'','char world ='W''和'char ex ='!''的颜色不同? – Shoe 2012-02-06 10:35:27