Lesson 18 +10 XP

Format Specifiers Overview

Format Specifiers Overview

Format specifiers tell printf and scanf the type of the value they're handling.

The most common ones

SpecifierPrints
%d or %iinteger
%ccharacter
%ffloat (decimal)
%lfdouble (long float)
%sstring
%uunsigned integer
%xhexadecimal (lowercase)

Example

int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c\n", myNum, myLetter);

Output:

My number is 15 and my letter is D

Spaces in output

The format controls exactly how much space appears. Add a space between words:

printf("%d cars\n", 12);   // 12 cars

Double has its own specifier

Use %lf for a double (it's "long float"):

double pi = 3.14159;
printf("%lf\n", pi);

TL;DR

  • %d = int, %c = char, %f = float, %lf = double, %s = string.
  • One placeholder per value, values in order.
  • printf only prints what the specifiers allow.