Search code examples
c++ccolorsansi-escape

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


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?


Solution

  • I'm afraid you forgot the ESC character:

    #include <cstdio>
    
    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)