Alex Rivera | Logout

How can I use ANSI Escape Codes for outputting colored text in C and C++?

Asked 2011-09-14T10:41:38.303
13

I read about ANSI-C escape codes here. Tried to use it in C/C++ printf/std::cout to colorize the text outputted to console, but without success.

My attempt:

#include <iostream>
#include <cstdio>

int main() {
    int a=3, b=5;
    int &ref = a;
    ref = b;
    
    //cout << "\155\32\m" << a << b <<'\n'; //here it prints m→m 5, no colored text
    printf("\155\32\m %d",a); //here to it prints same - m→m 5, 

    getchar();
}

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

Am I missing something?

Also, I remember that 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?

Edit
Report

1 Answer

8

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.

answered 2011-09-14T10:59:41.277

Your Answer