Printf
Conversions Table
Table
Argument Character | Argument Type | Printed as |
---|---|---|
d , i |
int |
decimal number. |
o |
int |
unsigned octal number (without a leading zero). |
x , X |
int |
unsigned hexadecimal number (without a leading 0x or 0X ), using abcdef or ABCDEF for 10, …, 15. |
u |
int |
unsigned decimal number. |
c |
int |
single character. |
s |
char * |
print characters from the string until a \0 or the number of characters given by the precision. |
f |
double |
[-]m.dddddd , where the number of d 's is given by the precision (default 6). |
e , E |
double |
[-]m.dddddde±xx or [-]m.ddddddE±xx , where the number of d 's is given by the precision (default 6). |
g , G |
double |
use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f . Trailing zeros and a trailing decimal point are not printed. |
p |
void * |
pointer (implementation-dependent representation). |
% |
no argument | print a % . |
Optional Arguments
Following are the optional arguments you can use.
Field Width
(the minimum amount of character space required insidestdout
).- Example:
%11s
makes afield width
of11
characters.
- Example:
Left Justification Flag
- Example:
%-10s
. If thestring
[^1] to be printed is smaller than thefield width
required, the characters will be left justified instead of being right justified by default.
- Example:
Precision
- Example:
%.4s
allows4
characters (in case ofstrings
[^1]) or4
digits after the decimal point infloat
values to be printed.
- Example:
#include <stdio.h>
int main () {
const char* test = "hello world";
printf(":%s:\n", test); // (1)!;
printf(":%10s:\n", test); // (2)!;
printf(":%.10s:\n", test); // (3)!;
printf(":%-10s:\n", test); // (4)!;
printf(":%.15s:\n", test); // (5)!;
printf(":%-15s:\n", test); // (6)!;
printf(":%15.10s:\n", test); // (7)!;
printf(":%-15.10s:\n", test); // (8)!;
return 0;
}
- Prints
:hello world:
. - Prints
:hello world:
. The field width10
was too small to fit in thestring
[^1] so some padding was needed. - Prints
:hello worl:
.String
[^1] is only printed with10
characters. - Prints
:hello world:
. There is no extra padding, therefore justification is irrelevant. - Prints
:hello world:
. More characters are allowed butstring
[^1] contains characters less than15
in count. - Prints
:hello world :
. Minimumfield width
is15
, creating some padding around thestring
.[^1] Then thestring
[^1] is left justified. - Prints
: hello worl:
. Minimumfield width
is15
, creating some padding around thestring
.[^1] But only10
characters are allowed due to precision. - Prints
:hello worl :
. Minimumfield width
is15
, creating some padding around thestring
.[^1] But only10
characters are allowed due to precision and thestring
[^1] is left justified.
References
- Read more about strings.