printf conversions in C
The format string is a small language: width, precision, and the right specifier per type.
#include <stdio.h>
void formats(void) {
int count = 42;
double rate = 91.5;
const char *name = "typestar";
size_t size = sizeof(count);
printf("%d %5d %-5d|\n", count, count, count);
printf("%.2f %8.3f %e\n", rate, rate, rate);
printf("%s %10s %-10s|\n", name, name, name);
printf("%zu bytes, %c, %x, %o\n", size, 'A', 255, 8);
printf("%p\n", (void *) name);
printf("%%d prints a literal percent\n");
}
How it works
%dis int,%uunsigned,%zusize_t,%pa pointer.%-8sleft-aligns in eight columns,%.2ffixes the decimals.- A mismatched specifier is undefined behavior, not a warning you may ignore.
Keywords and builtins used here
charconstdoubleformatsintsize_tsizeofvoid
The run, in numbers
- Lines
- 15
- Characters to type
- 404
- Tokens
- 119
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 79 seconds.
Step 1 of 2 in Input & output, step 31 of 35 in Language basics.