How to Print Bold and Styled Text in C

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.

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 (\033 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 –

How to Print Bold Text in C

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.

Printing Colored Text in C

In the above code, 1;31 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

Other Text Styling Effects in C

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

See Also

Leave a Comment