Full reference guide to C printf and scanf format specifiers: %d, %f, %s, %c, %p, width flags, and precision modifiers with tested code.
What are Format Specifiers in C?
In C programming, format specifiers (also called conversion specifiers) are placeholder tokens used within formatted I/O functions like printf(), scanf(), sprintf(), and sscanf().
A format specifier begins with a % character followed by characters that define how data should be formatted or parsed.
1. Common Format Specifiers Cheat Sheet
| Specifier | Data Type | Example Output / Usage |
|---|---|---|
%d or %i | Signed decimal integer | printf("%d", 45); -> 45 |
%u | Unsigned decimal integer | printf("%u", 300U); -> 300 |
%f | Floating-point (fixed decimal) | printf("%f", 3.14); -> 3.140000 |
%lf | Double precision float (required in scanf) | scanf("%lf", &dblVal); |
%c | Single character | printf("%c", 'A'); -> A |
%s | String of characters (null-terminated) | printf("%s", "hello"); -> hello |
%p | Memory pointer address (hexadecimal) | printf("%p", (void*)&x); -> 0x7ffee4 |
%x / %X | Unsigned hexadecimal integer (lowercase / uppercase) | printf("%X", 255); -> FF |
%o | Unsigned octal integer | printf("%o", 8); -> 10 |
%% | Prints a literal percent sign % | printf("100%%"); -> 100% |
2. Width, Precision, and Flag Modifiers
You can control field width, alignment, and decimal precision by placing modifiers between % and the conversion character:
%05d: Pad integer with leading zeros to minimum 5 width (e.g.00042).%-10s: Left-align string within a 10-character column.%.2f: Round floating-point value to exactly 2 decimal places.%+d: Force display of sign (+or-).
c (ISO Standard)#include <stdio.h> int main() { double price = 19.9542; int invoiceNum = 73; printf("Formatted Invoice: INV-%05d\n", invoiceNum); printf("Rounded Price: $%.2f\n", price); printf("Aligned Table: |%-10s|%8.2f|\n", "Apples", 4.5); return 0; }
3. Critical Scanf Traps & Best Practices
- Always pass address (
&) for primitive variables inscanf:c (ISO Standard)int age; scanf("%d", &age); /* Correct */ - Prevent Buffer Overflows with
%s: Specify field limits when reading strings to avoid stack smashing:c (ISO Standard)char username[32]; scanf("%31s", username); /* Reads max 31 chars + null terminator */
Related References & Guides
- Review fundamental types in the C Data Types Reference.
- Explore standard I/O library prototypes in C Standard Library Functions.
- Test formatting and parsing in the Online C Compiler.