Home > Back-end >  How can I specify the color of particular characters in a String in c?
How can I specify the color of particular characters in a String in c?

Time:11-20

I am experimenting with colorized text output to the console in c. I know that you are able to change the color of entire printf statements, but I was wondering if I am able to change the text color of individual characters within a printf statement. In summary, I would like to be able to print out "asdf" with the a being red, the s being green, the d being blue, and the f being orange. Thank you in advance.

CodePudding user response:

I have found a temporary work around: using multiple printf statements since they do not go to the next line, I do not like this solution very much so if anyone has a better solution please post it and I will accept it if it works well.

CodePudding user response:

First of all, in C, characters has no color. They are just numbers. So your question is not at all related to C, which doesn't care at all about how your print things.

What you are referring to, is the fact that some terminals accept some control characters to specific how they should render what is sent to them. Those are just special characters, that are not meant to be printed, but to modify the terminal behavior. There is no guarantee that your terminal understand those control characters. Nor is there any guarantee that they are the same control characters as other terminals.

Some library (such as ncurses) exist that have knowledge on the terminal you are using, and provide helper functions that make this transparent.

All that being said, the way to print in red (well, the most common one, at least) is

printf("\033[31m");

That switch the terminal to red and

printf("\033[m");

That switches is back to normal.

Those are control characters. So, from C point of view, just characters like any other, to be printed, that is sent to the terminal. It is then up to the terminal to do whatever it sees fit with it.

Being just characters like other, nothing prevent you to mix them with any normal characters,

So your example

printf("\033[31ma\033[32ms\033[34md\033[33mf\033[m\n");

But there is no guarantee it works. You can't really count on it. There is even no guarantee that it won't print some unwanted chars.

  • Related