C User Input
scanf reads a value typed by the reader. Until now every value was fixed in the code; scanf lets the reader supply it.
Read one number
The typed number lands in age. The print line shows it back: 25.
#include <stdio.h>
int main() {
int age = 0;
scanf("%d", &age);
printf("%d\n", age);
return 0;
}Read two numbers
Two whole numbers are read. The print line shows their sum, 7.
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
scanf("%d %d", &a, &b);
printf("%d\n", a + b);
return 0;
}Double the typed value
The typed number is doubled before printing. The print line shows 42.
#include <stdio.h>
int main() {
int n = 0;
scanf("%d", &n);
printf("%d\n", n * 2);
return 0;
}Example
#include <stdio.h>
int main() {
int age = 0;
scanf("%d", &age);
printf("You are %d.\n", age);
return 0;
}Key points
- scanf("%d", &age); reads a whole number and stores it in age.
- The & before age is part of the read, not decoration.
- & hands scanf the variable, so scanf can write the new value into it.
- Without the &, scanf has nowhere to put the typed value.
- Start each variable with a value before its scanf, such as int age = 0;.
- printf with %d prints the value that was read.
- scanf reads one value per %d in its text.
The typed value is 30, read into age. The print line shows it inside a sentence: You are 30.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the & do in scanf("%d", &age);?