How to use the ANSI Escape code for outputting colored text on Console

匿名 (未验证) 提交于 2019-12-03 01:54:01

问题:

I read about ANSI-C escape codes here. Tried to use it in C/C++ printf/cout to colorize the text outputted to consolde but without sucess.

Code:

#include    #include   int main() {      int a=3, b=5;     int &ref = a;      ref = b;      //cout 

How to use these escape codes to output colored text to console?

Am i missing something?

EDIT: In some C++ code I saw a call to this function

textcolor(10);

But it gives compilation errors in g++ and in Visual Studio. Which compiler had this function available? Any details?

回答1:

I'm afraid you forgot the ESC character:

#include   int main() {     printf("%c[%dmHELLO!\n", 0x1B, 32); }

Unfortunately it will only work on consoles that support ANSI escape sequences (like a linux console using bash, or old Windows consoles that used ansi.sys)



回答2:

I created a very simple text-management library some time ago, being multiplatform, it uses native API calls for Windows and ANSI escape sequences for the rest of the platforms. It is fully documented and you can also browse the source code.

About your specific question, I think you are missing some codes. For example, in order to change the color of text, you should use something like:

static const char * CSI = "\33["; printf( "%s%s", CSI, "31m" );   // RED

Hope this helps.



回答3:

ANSI escape codes worked on DOS using the ansi.sys device driver. They won't work windows xp or higher. You need to use the console API SetConsoleTextAttribute()

textcolor was available in the borland turbo c++ compiler.



回答4:

ANSI formatting codes aren't supported in windows.

http://en.wikipedia.org/wiki/ANSI_escape_code



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!