Back to Blog

C in 100 Seconds: scanf | Episode 12

Daryl WongDaryl Wong

Video: C in 100 Seconds: scanf — Read Numbers and Strings from the User | Episode 12 by Taught by Celeste AI - AI Coding Coach

Watch full page →

scanf — Reading User Input in C

C in 100 Seconds, Episode 12


printf sends data out. scanf brings data in. It reads formatted input from the terminal and stores it in your variables.

Reading an Integer

int age;
printf("Enter age: ");
scanf("%d", &age);
printf("You are %d years old\n", age);

The & is critical. scanf needs the address of the variable so it can write to it. Forget the ampersand and your program crashes or corrupts memory.

Reading a String

char name[50];
printf("Enter name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);

No & needed for arrays — the array name already decays to a pointer. But there's a catch: scanf("%s", ...) stops at the first whitespace. Type "John Smith" and you'll only get "John".

The Ampersand Rule

  • int, float, char — use & (pass the address)
  • Arrays (char name[]) — no & needed (already an address)

This is your first taste of pointers in action. scanf can't modify your variable unless it knows where that variable lives in memory.

Limitations of scanf

scanf is fine for quick prototypes, but it has sharp edges:
- No buffer overflow protection for strings
- Stops reading at whitespace
- Leftover newlines in the input buffer cause problems with consecutive reads

For safer string input, there's a better tool — which we'll cover next.

Full Code

#include <stdio.h>

int main() {
  int age;
  printf("Enter age: ");
  scanf("%d", &age);
  printf("You are %d years old\n", age);

  char name[50];
  printf("Enter name: ");
  scanf("%s", name);
  printf("Hello, %s!\n", name);

  return 0;
}

Compile and Run

gcc input.c -o input
./input

Next episode: fgets — the safe way to read string input.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode12