FORMATTERS FOR STRINGS/CHARACTERS
Consider the following program.
#include <stdio.h> main() /* FORMATS.C */ { char c = '#'; static char s[] = "helloandwelcometoclanguage"; printf("Characters:\n"); printf("%c\n", c); printf("%3c%3c\n", c, c); printf("%-3c%-3c\n", c, c); printf("Strings:\n"); printf("%s\n", s); printf("%.5s\n", s); printf("%30s\n", s); printf("%20.5s\n", s); printf("%-20.5s\n", s); }
The output of the above program will be,
Characters: # # # # # Strings: helloandwelcometoclanguage hello helloandwelcometoclanguage hello hello
The statement printf("%.5s\n",s) means print the first five characters of the array s. The statement printf("%30s\n", s) means that the array s is printed right justified, with leading spaces, to a field width of thirty characters.
The statement printf("%20.5s\n", s) means that the first five characters are printed in a field size of twenty which is right justified and filled with leading spaces.
The final printf statement uses a left justified field of twenty characters, trailing spaces, and the .5 indicating to print the first five characters of the array s.