Home > Blockchain >  C, how to change color of text with user input?
C, how to change color of text with user input?

Time:10-16

In C language, there is this function

system("Color x")

Which changes the color of console text. However i've been wondering how to use this function with user input, by entering desired color, for example:

char color;
printf("Enter color: "); //user enters A/B/C etc.
scanf(" %c", &color);
system("Color %c", color);

CodePudding user response:

The system command doesn't accept parameters in the same way the print family of commands does (i.e. a format string followed by a variable argument list with variable names). The solution is to build the desired string first using sprintf. First, allocate memory for the target string:

char cmd[8]; // E.g. "Color x" has 8 chars when including the null terminator.

Then, use sprintf to combine the format string and variable, and write the result to cmd:

sprintf(cmd, "Color %c", color);

Finally, call system using the string just written to:

system(cmd);

This is assuming that you want to use this method for changing colors. For a better approach, see here.

  • Related