C Format Specifiers
A format specifier tells printf where to put a value and how to show it. It starts with % and ends with a letter that matches the type of the value. Using the wrong letter prints nonsense, and the compiler warns about it with -Wall.
The common specifiers
| Specifier | Prints | Example value |
|---|---|---|
%d or %i | int (whole number) | 42 |
%ld | long | 100000L |
%lld | long long | 5000000000LL |
%u | unsigned int | 7u |
%f | float or double | 3.140000 |
%e | number in exponent form | 3.140000e+00 |
%c | char (one character) | 'A' |
%s | string (text) | "Asha" |
%x | int in hexadecimal | ff |
%p | a pointer (memory address) | address |
%% | a percent sign itself | % |
#include <stdio.h>
int main(void) {
int count = 42;
double price = 19.5;
char grade = 'B';
char name[] = "Asha";
printf("count = %d\n", count);
printf("price = %f\n", price);
printf("grade = %c\n", grade);
printf("name = %s\n", name);
printf("255 in hexadecimal is %x\n", 255);
printf("Discount: 10%%\n");
return 0;
}count = 42 price = 19.500000 grade = B name = Asha 255 in hexadecimal is ff Discount: 10%
Decimals
%f shows six digits after the decimal point. Write the number of decimals you want between % and f: %.2f shows two, %.0f none (rounded).
#include <stdio.h>
int main(void) {
double pi = 3.14159265;
printf("%f\n", pi);
printf("%.2f\n", pi);
printf("%.4f\n", pi);
printf("%.0f\n", pi);
return 0;
}3.141593 3.14 3.1416 3
Field width: lining up columns
A number before the letter sets the minimum width. Numbers and text are moved to the right of that width; a minus sign moves them to the left. This lines up columns in a table.
#include <stdio.h>
int main(void) {
printf("%-8s%6s\n", "Item", "Price");
printf("%-8s%6.2f\n", "Pen", 1.5);
printf("%-8s%6.2f\n", "Notebook", 12.25);
printf("[%5d]\n", 42);
printf("[%-5d]\n", 42);
printf("[%05d]\n", 42);
return 0;
}Item Price Pen 1.50 Notebook 12.25 [ 42] [42 ] [00042]
%05d fills the width with zeros instead of spaces, which is useful for codes such as 00042.
Reading values with scanf
scanf, which reads input, uses almost the same specifiers. One important difference: for a double, printf uses %f but scanf needs %lf. The User Input topic covers scanf in detail.
Practice exercises
- Print your height in metres with exactly two decimals.
- Print a three-row table of names and marks with the names on the left and the marks lined up on the right.
- Print the numbers 10, 100 and 255 in hexadecimal.
- Print an
intwith%fand read the warning. Fix the specifier.