Reading input with scanf
How to read numbers and words from the keyboard in C with scanf, and how to check that it worked.
scanf reads text from standard input and converts it, using the same kind of format codes as printf. It needs the address of each variable to fill in, so you pass &x, not x.
scanf returns how many values it successfully read. Always check it: if the user types letters where a number was expected, nothing is stored.
For a word, %s reads up to the next space; always give a maximum width like %19s for a 20-byte array so long input can't overflow it. For whole lines, fgets is safer.
Example
#include <stdio.h>
int main(void) {
int a, b;
if (scanf("%d %d", &a, &b) != 2) {
printf("please type two numbers\n");
return 1;
}
printf("%d\n", a + b);
return 0;
}
Output:
7