How to Print Bold and Styled Text in C. When working in C, you often need visual flair console output, such as bold or styled text. It can be particularly useful for creating more user-friendly interfaces. C does not have built-in functions for styling console output, but you can achieve this effect using ANSI escape codes, which are a sequence of bytes that control the formatting of console output. This tutorial will guide you on how we can implement bold and other styled text in our C program.
Table of Contents
Understanding ANSI Escape Codes
ANSI escape codes are used to control the formatting, color, and other output on the video text terminal. To use ANSI escape codes, we write a sequence of characters starting with an escape character (\0
33 or \e
) followed by ‘[` and followed by some other characters that specify the actions.
How to Print Bold Text in C
To print bold text in C, We can use the escape code ‘\033[1m`, where ‘1’ activates the bold effect. Here is a simple example –
#include <stdio.h>
void main()
{
printf("\033[1m This text will be bold\033[0m");
}
In the above example ‘\033[1m` initiates bold text, and ‘\033[0m` reset the formatting to default, which is important to avoid unwanted formatting in the subsequent text.
Printing Colored Text in C
Adding colors works similarly to making text bold. We can use different codes for different colors. Here is an example of how to print text in red in C language.
#include <stdio.h>
void main()
{
printf("\033[1;31m This text will be bold and red\033[0m");
}
In the above code, 1;3
1 specifies bold and red. The number ’31’ is the ANSI code for red text. Like the bold text example ‘\033[0m` resets the formatting.
Other Text Styling Effects in C
Besides bold and colors, ANSI code can be used for a variety of other effects, such as underlining, blinking, reversed color, and more. Here is how we can apply these styles.
- Underline: ‘\033[4m`
- Blinking: ‘\033[5m`
- Reversed(swap foreground and background colors): ‘\033[7m`
Example for underlined text in C
#include <stdio.h>
void main()
{
printf("\033[4m This text will be underlined\033[0m");
}
Limitations and Compatibility
It is important to note that ANSI escape codes may not work in all environments. Some older terminals or command prompts might not support this features, and the appearance may vary across different systems and terminal configurations. If portability is a concern, consider alternative methods such as using libraries like ‘ncurses’ for Unix-like systems, which offer more control and flexibility for handling console output.
Happy Coding & Learning