C: Change color of letters (multiple colors on one screen)

4

For example, I want to start on the same screen:

printf(".___. .___. .___.\n");

printf("._1_. ._2_. ._3_.\n");

printf("Digite 0 p/ sair ou outro número p/ continuar: ");

But I want the letters of each printf to have different colors, for example: first blue, then green and then yellow ... I tried to use the following code:

system("color A");
printf(".___. .___. .___.\n");
system("color E");  
printf("._1_. ._2_. ._3_.\n");
system("color 7");   
printf("Digite 0 p/ sair ou outro número p/ continuar: ");

But it did not work; he picked up only the last color, or rather he was quick and only visibly executed the last color ... I also tried:

#include <conio.h>
textcolor(blue);
printf(".___. .___. .___.\n");
textcolor(red); 
printf("._1_. ._2_. ._3_.\n");
textcolor(yellow);  
printf("Digite 0 p/ sair ou outro número p/ continuar: ");

But it says that textcolor has not been declared.

    
asked by anonymous 12.06.2015 / 06:32

2 answers

0

An easy way to do this in C is to use the ANSI color code. At first you create a constant to store ANSI for each color :

#define ANSI_COLOR_RED      "\x1b[31m" //cores em ANSI utilizadas 
#define ANSI_COLOR_GRAY     "\e[0;37m"

And to use, pass these constants in printf :

printf(ANSI_COLOR_RED "Hello world" ANSI_COLOR_RESET); 

The first one is the color you want for this text, and in the end you can use the Reset to return to the default.

Here has an example where I used this in a game.

    
04.10.2018 / 04:56
-2

Since you are looking for a specific C solution for windows, I would recommend using the SetConsoleTextAttribute() function of the win32 API. You have to generate a handler for the terminal and then feed it with the correct attributes.

Here's a simple example:

/* Mudar a cor do texto do terminal, e depois de volta ao normal. */
#include <stdio.h>
#include <windows.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    WORD saved_attributes;

    /* Salvar estado atual */
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    saved_attributes = consoleInfo.wAttributes;

    SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
    printf("This is some nice COLORFUL text, isn't it?");

    /* Voltando ao estado original */
    SetConsoleTextAttribute(hConsole, saved_attributes);
    printf("Back to normal");

    return 0;
}

For more information, see here .

    
10.07.2015 / 16:58