Asking the user for a value
So far our programs always print the same thing. To make them interactive, we read what the user types. In C we do this with scanf (say "scan-eff"). It works like printf in reverse:
#include <stdio.h>
int main() {
int age;
printf("How old are you? ");
scanf("%d", &age);
printf("Next year you will be %d.\n", age + 1);
return 0;
}Input (what the user types)
14
Output
How old are you? Next year you will be 15.
int age;makes an empty box for the number."%d"tellsscanfto read a whole number.&agetellsscanfwhere to put it: in the boxage.
What is the &?
The & means "the address of". scanf needs to know where the box is in memory, so it can put the number inside. For now, just remember: with scanf, put & before the variable name. Module 9 explains addresses properly.
Think of it like this: Giving
scanfthe variable without&is like asking a delivery driver to bring a parcel but not telling them your address.
Common mistake: Forgetting the
&:scanf("%d", age);compiles, but crashes or does something strange when it runs.
Reading several values
One scanf can read several values. The user can separate them with spaces or new lines:
#include <stdio.h>
int main() {
int a, b;
printf("Type two numbers: ");
scanf("%d %d", &a, &b);
printf("%d + %d = %d\n", a, b, a + b);
return 0;
}Input (what the user types)
7 5
Output
Type two numbers: 7 + 5 = 12
Tip:
int a, b;creates twointvariables in one line.
Reading decimals and characters
Use the same placeholders as printf, with one exception: to read a double you write %lf ("long float"):
| To read a... | Use |
|---|---|
int | scanf("%d", &x); |
double | scanf("%lf", &x); |
char | scanf(" %c", &x); (note the space before %c) |
#include <stdio.h>
int main() {
double price;
char size;
scanf("%lf", &price);
scanf(" %c", &size);
printf("Size %c costs %.2f\n", size, price);
return 0;
}Input (what the user types)
4.5 M
Output
Size M costs 4.50
The space in " %c" tells scanf to skip any spaces or Enter key presses left over from earlier input, and read the next real character.
Remember:
scanf("%d", &x)reads an int,%lfreads a double," %c"reads a char. Don't forget the&!