How to underline text using printf in C

21,430

Solution 1

It is not possible to do so using any standard C functions, as the C language doesn't even recognize the presence of a screen.

With Windows API console functions you can change colors, underline and some other things. The particular function you are looking for is called SetConsoleTextAttribute just as in the post you linked. Change its attributes to include COMMON_LVB_UNDERSCORE.

Solution 2

You might run your program in some environment with a terminal accepting ANSI escape codes.

(I never used Windows - since I am using Linux only -, so I don't know how to set up such environment in Windows; but I heard that it is possible)

With ANSI escape codes, underlining is "\e[4m" with \e being the ASCII ESCAPE character.

Solution 3

Perhaps try using termcaps. Something like this (after initializing termcaps) :

printf(tgetstr("us", NULL)); /* underline on */
printf(""/* your string */);
printf(tgetstr("ue", NULL)); /* underline off */

or more concise :

printf("%s/* your text here */%s", tgetstr("us", NULL), tgetstr("ue", NULL));

https://www.gnu.org/software/termutils/manual/termcap-1.3/html_node/termcap_34.html

Share:
21,430
Toby
Author by

Toby

Updated on June 21, 2020

Comments

  • Toby
    Toby almost 4 years

    I note the question Colorful text using printf in C gives a good example of setting coloured text on the standard console output in Windows. Is there something similar that allows output to be underlined? Or possibly even bolded or italicised?

    EDIT: I tried Lundin's answer on using COMMON_LVB_UNDERSCORE with no luck. Attempting to use AddFontResource() to add arial italic font to try italics gives an error that there is an undefined reference to __imp_AddFontResourceA