C Format Specifiers
When you print a variable in C with printf, you must tell it what kind of value you are printing. You do this with a format specifier: a small placeholder that starts with a percent sign. The specifier is swapped out for the real value when the program runs.
What Is a Format Specifier?
A format specifier is a placeholder inside a string that tells printf how to display a value. For example %d means "insert an integer here" and %s means "insert a string of characters here".
Printing an integer with %d
#include <stdio.h>
int main() {
int items = 7;
printf("You have %d items.\n", items);
return 0;
}Common Specifiers
Each data type has its own specifier. Here are the ones you will use most often as a beginner.
Format specifiers by type
Using Several Specifiers at Once
You can place many specifiers in one string. printf fills them left to right using the values you list after the string, in the same order.
Mixing specifiers in one printf
#include <stdio.h>
int main() {
char grade = 'A';
int marks = 95;
float average = 88.5;
printf("Grade %c, marks %d, average %.1f\n", grade, marks, average);
return 0;
}Notice %.1f in the example above. Adding .1 tells printf to show only one digit after the decimal point, which keeps decimal output tidy.
Controlling decimal places
#include <stdio.h>
int main() {
float price = 4.99;
printf("Total: %.2f\n", price);
return 0;
}