The Analogy: A Fill-in-the-Blanks Form
printf is not a print statement. It is a form with blanks in it, and you supply the values that go in the blanks.
"Dear ____, your balance is $____ as of ____." Hand that form to printf along with a name, a number, and a date, and it fills the blanks in order. The blanks are the % specifiers, and each one declares what kind of thing belongs there — a whole number, a decimal, a character, a string.
The catch is that the form does not check your answers. If a blank says "put a whole number here" and you hand it a decimal, printf will read four bytes out of an eight-byte value and print whatever that happens to mean. scanf is the same form running backwards, and it is even less forgiving, because it writes into your memory rather than reading from it.
Syntax or Core Structure
#include <stdio.h>
int main(void) {
int quantity = 3;
double price = 4.5;
char initial = 'R';
char city[] = "Lisbon";
printf("Quantity: %d\n", quantity);
printf("Price: %.2f\n", price);
printf("Initial: %c\n", initial);
printf("City: %s\n", city);
printf("Total: %d items at %.2f = %.2f\n",
quantity, price, quantity * price);
return 0;
}
Output:
Quantity: 3
Price: 4.50
Initial: R
City: Lisbon
Total: 3 items at 4.50 = 13.50
The arguments are consumed strictly left to right, one per specifier. Supply too few and printf reads whatever garbage is next in the argument registers; supply too many and the extras are silently ignored.
The specifiers you will actually use
| Specifier | Reads / prints | Example output |
|---|---|---|
%d | int in decimal | -42 |
%u | unsigned int | 4294967295 |
%ld / %lld | long / long long | 9000000000 |
%f | double (and float, promoted) | 3.140000 |
%.2f | double, two decimals | 3.14 |
%e | scientific notation | 3.14e+00 |
%c | single char | A |
%s | string, up to the \0 | Lisbon |
%x / %o | hexadecimal / octal | ff / 377 |
%p | a pointer's address | 0x7ffd3c1a |
%zu | size_t, as from sizeof | 8 |
%% | a literal percent sign | % |
Width, precision, and alignment
#include <stdio.h>
int main(void) {
printf("[%5d]\n", 42); // width 5, right aligned
printf("[%-5d]\n", 42); // width 5, left aligned
printf("[%05d]\n", 42); // pad with zeros
printf("[%8.3f]\n", 3.14159); // width 8, 3 decimals
printf("[%-10s|]\n", "hi"); // strings pad too
printf("[%+d] [%+d]\n", 42, -42);
return 0;
}
Output:
[ 42]
[42 ]
[00042]
[ 3.142]
[hi |]
[+42] [-42]
The general shape is %[flags][width][.precision]specifier. This is how you get columns to line up in a report without doing any arithmetic yourself.
Technical Depth: Why scanf Is Dangerous
scanf writes into memory you name. That means every call is a chance to write somewhere you did not intend.
#include <stdio.h>
int main(void) {
int age = 0;
printf("Age: ");
if (scanf("%d", &age) != 1) { /* note the & */
printf("That was not a number.\n");
return 1;
}
printf("You are %d\n", age);
return 0;
}
Three things in that tiny program are load-bearing:
- The
&.scanfneeds the address ofageso it can store into it. Writingscanf("%d", age)passes the current value ofage— likely0— andscanftreats it as an address and writes there. That is an immediate segmentation fault on a good day and silent corruption on a bad one. - The return value.
scanfreturns the number of items it successfully converted, orEOF. If the user types "banana", it converts nothing, returns 0, and leavesageuntouched. - No
&for arrays.scanf("%s", name)is correct withchar name[50], because an array name already decays to the address of its first element.
The leftover newline problem
#include <stdio.h>
int main(void) {
int count = 0;
char code = 0;
printf("Count: ");
scanf("%d", &count);
printf("Code letter: ");
scanf(" %c", &code); /* the leading space is essential */
printf("count=%d code=%c\n", count, code);
return 0;
}
When you type 5 and press Enter, %d consumes the 5 and leaves the \n sitting in the input buffer. The next %c would happily read that newline as your "code letter". The leading space in " %c" tells scanf to skip any amount of whitespace first. %d, %f, and %s skip leading whitespace automatically; %c is the exception.
Bounding string input
char name[50];
scanf("%s", name); /* DANGEROUS: no limit, will overflow past 50 */
scanf("%49s", name); /* safe: at most 49 chars plus the '\0' */
Unbounded %s is the classic buffer overflow. The width must be one less than the array size, because scanf adds the terminating zero itself.
When you want a whole line
#include <stdio.h>
#include <string.h>
int main(void) {
char line[100];
printf("Full name: ");
if (fgets(line, sizeof line, stdin) == NULL) {
return 1;
}
line[strcspn(line, "\n")] = '\0'; /* trim the trailing newline */
printf("Hello, [%s]\n", line);
return 0;
}
Output:
Full name: Grace Hopper
Hello, [Grace Hopper]
scanf("%s") stops at the first space, so it can never read "Grace Hopper" as one value. fgets reads the whole line, bounded by the buffer size, and keeps the newline — which is why the strcspn line trims it. For interactive input, fgets plus parsing is almost always the better choice.
scanf versus fgets
scanf | fgets | |
|---|---|---|
| Reads | one token at a time | one whole line |
| Stops at | whitespace | newline or buffer full |
| Bounds | only if you write the width | always, via the size argument |
| Leaves newline in buffer | yes | no, it consumes it |
| Handles "Grace Hopper" | no, stops at the space | yes |
| Failure signal | count of items converted | NULL |
Real World Example: An Invoice Line Printer
#include <stdio.h>
#include <string.h>
int main(void) {
char item[40];
int quantity = 0;
double unit_price = 0.0;
printf("Item description: ");
if (fgets(item, sizeof item, stdin) == NULL) return 1;
item[strcspn(item, "\n")] = '\0';
printf("Quantity: ");
if (scanf("%d", &quantity) != 1) {
printf("Quantity must be a whole number.\n");
return 1;
}
printf("Unit price: ");
if (scanf("%lf", &unit_price) != 1) { /* %lf for double in scanf */
printf("Price must be a number.\n");
return 1;
}
double subtotal = quantity * unit_price;
double tax = subtotal * 0.20;
printf("\n%-20s %5s %10s %10s\n", "ITEM", "QTY", "UNIT", "AMOUNT");
printf("%-20s %5d %10.2f %10.2f\n", item, quantity, unit_price, subtotal);
printf("%-20s %5s %10s %10.2f\n", "VAT at 20%", "", "", tax);
printf("%-20s %5s %10s %10.2f\n", "TOTAL", "", "", subtotal + tax);
return 0;
}
Output:
Item description: USB-C cable, 2m
Quantity: 3
Unit price: 8.50
ITEM QTY UNIT AMOUNT
USB-C cable, 2m 3 8.50 25.50
VAT at 20% 5.10
TOTAL 30.60
The column alignment is done entirely with width specifiers, which is why the numbers line up without a single space being counted by hand. %-20s left-aligns the description in a twenty-character field; %10.2f right-aligns money in a ten-character field with two decimals. Note %lf in scanf versus %f in printf for the same double: printf promotes float to double automatically so both work, but scanf receives an address and must be told the exact width, so %f there would write only four bytes and corrupt the variable.
Common Mistakes
- Forgetting the
&on a numericscanf. The most common crash in beginner C. - Adding an
&to an array:scanf("%s", &name)wherenameischar[50]. It usually works by accident, and it is wrong. - Unbounded
%s, allowing input longer than the array. - Using
%finscanffor adouble. It must be%lf, or you write four bytes into eight and corrupt neighbours. - Reading a
charwith%cright after%dand getting the leftover newline instead of the character. - Ignoring
scanf's return value, then computing with a variable that was never assigned. - Mixing
scanfandfgetswithout clearing the buffer, sofgetsimmediately returns an empty line. - Writing
%sfor a singlechar.printf("%s", 'A')treats the value 65 as an address and crashes. - Assuming output appears immediately. Standard output to a terminal is line-buffered, so a prompt without
\nmay not show until something flushes it.
Best Practices
- Use
fgetsplussscanforstrtolfor interactive input; keep barescanffor exercises and throwaway tools. - Always check the return value of
scanfandfgets. - Always give
%sa width, one less than the array size. - Write
sizeof bufferrather than repeating the literal size, so the two can never drift apart. - Put a leading space before
%cunless you specifically want the whitespace. - Use width and precision specifiers to align tables rather than padding with spaces by hand.
- Print prompts without
\nonly if you alsofflush(stdout); otherwise end them with a newline. - Compile with
-Wall, which checksprintfandscanfformat strings against the arguments you passed.
Practice Exercises
- Break It On Purpose: Write a program that reads an
intwithscanfbut omit the&. Compile with-Wall, read the warning, run it, then fix it and describe what happened. - The Newline Hunt: Read an
intand then acharusing"%c"with no leading space. Show that the character is the newline, then fix it with" %c". - Receipt Formatter: Read three item names and prices with
fgetsandsscanf, then print them as a right-aligned table with a total row, using only width specifiers for alignment. - Safe by Construction: Write a program with a
char buf[8]that reads a word with a bounded%s, then prove with a long input that nothing beyond the buffer is written and the string is still terminated.