Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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

SpecifierPrintsExample value
%d or %iint (whole number)42
%ldlong100000L
%lldlong long5000000000LL
%uunsigned int7u
%ffloat or double3.140000
%enumber in exponent form3.140000e+00
%cchar (one character)'A'
%sstring (text)"Asha"
%xint in hexadecimalff
%pa 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;
}
Output
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;
}
Output
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;
}
Output
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

  1. Print your height in metres with exactly two decimals.
  2. Print a three-row table of names and marks with the names on the left and the marks lined up on the right.
  3. Print the numbers 10, 100 and 255 in hexadecimal.
  4. Print an int with %f and read the warning. Fix the specifier.