The printf format is a generalized name for a family of functions used to format output to various streams of values of different types, formatted according to a given template.
This template is determined by the string (format string) compiled according to special rules.
%[0][width][.param]type
The square brackets
[..]enclose optional parameters.
Only the%typeconstruction is required, everything else is additional format modifiers.
| Parameter | Description | |
|---|---|---|
type |
format specifier: | |
d, i |
Signed integer | |
u |
Unsigned integer | |
x, X |
Unsigned integer (in hexadecimal):X - uppercase characters;x - lowercase characters. |
|
f, F |
Floating point number (in normal form d.ddd) |
|
e, E |
Floating point number (in exponential notation d.ddde±dd) |
|
g, G |
Floating point number (in normal or exponential form) | |
a, A |
Floating point number (in hexadecimal):A - uppercase characters;a - lowercase characters. |
|
s |
текстовая строка | |
c |
text string | |
width |
Length of the field to be inserted. If the result after formatting exceeds this value, it will be cut off on the right. |
|
0 |
Only for numeric types. Fill with zeros on the left. If the result after formatting is less than width, then it will be padded with 0 on the left (if the parameter is not used, it will be padded with space characters). |
|
.param |
For floating point numbers - the number of characters after the decimal point. For a text string - the length of the string. |
|
For clarity, spaces in the"Result column are replaced with the sign
_.
| Argument Value | Format | Description | Result |
|---|---|---|---|
value0 = 109 |
{0} |
Default format | 109 |
{0%6d} |
Integer, length 6 characters | ___109 |
|
{0%06d} |
Integer, 6 characters long, filled with zeros | 000109 |
|
{0%x} |
Integer in hexadecimal | 6d |
|
{0%4X} |
Integer in hexadecimal, 4 characters long, uppercase characters | __6D |
|
{0%04x} |
Hexadecimal integer, 4 characters long, filled with zeros | 006d |
|
{0%c} |
One character | m |
|
value1 = 12.123456 |
{1%f} |
Floating point number | 12.123456 |
{1%.3f} |
Floating point number, 3 decimal places | 12.123 |
|
{1%9.4f} |
Число с плавающей точкой, длина 9 символов, 4 цифры после запятой | __12.1235 |
|
{1%09.4f} |
Число с плавающей точкой, длина 9 символов, 4 цифры после запятой | 0012.1235 |
|
value2 = 'text' |
{2%c} |
One character | t |
{2%.4s} |
Text string, length 4 characters | text |
|
{2%.2s} |
Text string, length 2 characters | te |