Scanning integers and floats
What you'll learn: How to use format specifiers to capture numeric data from a user and store it in variables.
The Post Office Analogy
Think of scanf as a postal worker delivering a package to a specific house. For the delivery to work, two things must be true: the worker needs to know what kind of package it is (a small envelope or a heavy box), and they need the exact address of where to put it.
In C, the "package type" is the format specifier, and the "address" is the location of your variable in your computer's memory.
Using %d and %f
To read a whole number (an integer), we use the %d specifier. For numbers with decimals (floats), we use %f.
The most critical part of scanf is the ampersand symbol (&) placed before the variable name. In C, the & operator literally means "address of." If you forget it, you aren't giving scanf a place to store the data; you're just giving it a value, which will cause your program to crash.
Putting it into Practice
Here is how you ask a user for their age and their favorite decimal number:
#include <stdio.h>
int main() {
int age;
float price;
printf("Enter your age: ");
// Use %d for integers and & to point to the address
scanf("%d", &age);
printf("Enter the price of coffee: ");
// Use %f for floats and & to point to the address
scanf("%f", &price);
printf("You are %d years old and your coffee costs $%.2f.\n", age, price);
return 0;
}
How it behaves
When scanf runs, the program pauses and waits for the user to type. It ignores "whitespace"—things like spaces, tabs, or new lines—until it finds the number. Once the user presses Enter, scanf grabs the digits, converts them into a format the computer understands, and tucks them into the variable's "address" provided by the & symbol.
If the user types letters instead of numbers, scanf will fail to read the data correctly, but for now, focus on the matching: %d for int and %f for float.
Key takeaway
Always use the %d or %f specifiers to match your variable type, and never forget the & (address-of) operator when using scanf.