C User Input (scanf)
The scanf() function reads input typed by the user from the keyboard. Like printf, it uses format specifiers to know what type of data to expect.
Unlike printf, scanf needs the memory address of each variable (using the & operator) so it can write the input directly into that variable's memory.
scanf("format", &variable);Reading numbers
To read an integer, use `scanf("%d", &age);`. The & gives scanf the address of age so it can store the typed value there directly.
Reading strings
To read a string, use `scanf("%s", name);` โ arrays already decay to a pointer/address, so no & is needed. Note that %s stops reading at the first whitespace.
#include <stdio.h>
int main() {
int age;
printf("Enter age: ");
scanf("%d", &age);
printf("You are %d\n", age);
return 0;
}Enter age: 25
You are 25scanf reads an integer typed by the user and stores it in age via its address.
#include <stdio.h>
int main() {
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Hi, %s!\n", name);
return 0;
}Enter name: Sam
Hi, Sam!name is a char array, so no & is needed since its name already refers to its address.
Key points
- scanf() needs & before variable names for basic types.
- Arrays (like strings) already act as addresses, so no & is used.
- %s in scanf stops reading at the first whitespace.
- Always ensure buffer sizes are large enough to avoid overflow.
