C ยท Chapter 21 of 45

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.

Syntax
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.

Example 1 (c)
#include <stdio.h>

int main() {
  int age;
  printf("Enter age: ");
  scanf("%d", &age);
  printf("You are %d\n", age);
  return 0;
}
Output
Enter age: 25
You are 25

scanf reads an integer typed by the user and stores it in age via its address.

Example 2 (c)
#include <stdio.h>

int main() {
  char name[20];
  printf("Enter name: ");
  scanf("%s", name);
  printf("Hi, %s!\n", name);
  return 0;
}
Output
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.
๐Ÿ’ก Note: Forgetting the & operator with scanf is one of the most common beginner mistakes in C.

๐Ÿ“ Quick Quiz

1. Why does scanf need the & operator for int variables?

2. Does scanf need & when reading into a char array?

3. What does %s in scanf stop reading at?