~/C Printf Essential Tips and Tricks
Sep 14, 2021
Use printf for formatted output in C. Here are concise practical tips:
Format Specifiers
Use %d
for integers, %f
for floats, %s
for strings. To print a literal percent sign, use %%
.
Field Width and Precision
Set width or precision by numbers in the specifier, like %6d
for six spaces or %.2f
for two decimals.
Code example:
|
|
Output:
|
|
Print Hex and Octal
Use %x
or %X
for hex and %o
for octal (see format specifiers).
Code example:
|
|
Align Output
Use -
for left alignment: %-10s
will left align a string in 10 characters.
Printing Pointers
Use %p
for addresses.
Print Leading Zeros
Use 0
before width for leading zeros, e.g. %05d
prints 00042
.
Multiple Variables
You can print values in order by passing multiple arguments:
|
|
Important
Always match format specifiers to argument types to avoid bugs or undefined behavior.
For more details, check the C documentation.