C Format Specifiers

A format specifier tells printf() and scanf() what kind of value to print or read. It starts with %.

Common format specifiers

SpecifierUsed forExample value
%d or %iint25
%uunsigned int3000000000
%ldlong123456789
%ffloat (print)3.140000
%lfdouble (scanf)3.14
%cchar'A'
%sstring"Hello"
%xhexadecimalff
%ooctal17
%escientific1.5e+03
%%percent sign%

Example

#include <stdio.h>

int main(void) {
    int n = 255;
    double pi = 3.14159265;

    printf("Decimal: %d\n", n);
    printf("Hex: %x\n", n);
    printf("Octal: %o\n", n);
    printf("Float: %f\n", pi);
    printf("Two decimals: %.2f\n", pi);
    printf("Char: %c\n", 'A');
    printf("String: %s\n", "C language");
    printf("Percent: 50%%\n");
    return 0;
}

Output:

Output of the above program is

Decimal: 255
Hex: ff
Octal: 377
Float: 3.141593
Two decimals: 3.14
Char: A
String: C language
Percent: 50%

Width and alignment

A number between % and the letter sets the minimum width. A minus sign aligns the value to the left. A zero fills with zeros.

#include <stdio.h>

int main(void) {
    printf("[%5d]\n", 42);
    printf("[%-5d]\n", 42);
    printf("[%05d]\n", 42);
    printf("[%8.2f]\n", 3.14159);
    return 0;
}

Output:

Output of the above program is

[ 42]
[42 ]
[00042]
[ 3.14]

Note: printf() uses %f for both float and double, but scanf() needs %f for float and %lf for double.

Next: C Type Casting.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.