Source: https://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/format.html
printf formatting is controlled by 'format identifiers' which, are shown below in their simplest form.
%d %i Decimal signed integer. %o Octal integer. %x %X Hex integer. %u Unsigned integer. %c Character. %s String. See below. %f double %e %E double. %g %G double. %p pointer. %n Number of characters written by this printf. No argument expected. %% %. No argument expected. |
These identifiers actually have upto 6 parts as shown in the table below. They MUST be used in the order shown.
% |
Flags |
Minimum field width |
Period |
Precision max field width |
Argument Type |
Required | Optional | Optional | Optional | Optional | Required |
The % marks the start and therfore is manatory.
- Left justify. 0 Field is padded with 0's instead of blanks. + Sign of number always O/P. blank Positive values begin with a blank. # Various uses: %#o (Octal) 0 prefix inserted. %#x (Hex) 0x prefix added to non-zero values. %#X (Hex) 0X prefix added to non-zero values. %#e Always show the decimal point. %#E Always show the decimal point. %#f Always show the decimal point. %#g Always show the decimal point trailing zeros not removed. %#G Always show the decimal point trailing zeros not removed. |
printf(" %-10d \n", number); printf(" %010d \n", number); printf(" %-#10x \n", number); printf(" %#x \n", number); |
main() { int number = 5; char *pointer = "little"; printf("Here is a number-%4d-and a-%10s-word.\n", number, pointer); } /********************************* * * Program result is: * * Here is a number- 5-and a- little-word. * *********************************/ |
As you can see, the data is right justified within the field. It can be left justified by using the - flag. A max string width can also be specified.
The width can also be given as a variable as shown below.
main() { int number=5; printf("---%*d----\n", 6, number); } /********************************* * * Program result is: * * ---- 5--- * *********************************/ |
The * is replaced with the supplied int to provide the ability to dynamically specify the field width.
%8.2fThis says you require a total field of 8 characters, within the 8 characters the last 2 will hold the decimal part.
%.2fThe example above requests the minimum field width and the last two characters are to hold the decimal part.
%4.8sSpecifies a minimum width of 4 and a maximum width of 8 characters. If the string is greater than 8 characters, it will be cropped down to size.
main() { int number=5; char *pointer="little"; printf("Here is a number %d and a %s word.\n", number, pointer); } /********************************* * * Program result is: * * Here is a number 5 and a little word. * *********************************/ |