Making Programs Interactive
A program that only prints is a lecture. A program that takes input is a conversation. scanf (scan formatted) is the primary way we get data from the user's keyboard.
The Syntax
int myNumber;
scanf("%d", &myNumber);
- The Format Specifier (
"%d"): Tellsscanfwhat type of data to expect. It must match your variable type! - The Ampersand (
&): The "Address-of" operator. This is the #1 source of errors for C students.
Why is the & required?
Think of your variable myNumber as a box in memory. If you just pass myNumber to scanf, you are passing the value currently inside the box (which is garbage). scanf doesn't want the value; it wants to know where the box is so it can put a new value inside. The & gives scanf the location (address) of that box.
Reading Multiple Items
You can read multiple pieces of data in one line:
int h, m, s;
printf("Enter time (HH:MM:SS): ");
scanf("%d:%d:%d", &h, &m, &s);
The user must type the colons : exactly as shown in the format string. If they type spaces instead, scanf will fail to read the remaining numbers.
The Input Buffer Problem
When you type "25" and press Enter, your variable gets the 25, but the "Enter" (\n) stays in a temporary storage area called the input buffer. If your next line is scanf("%c", &ch), it will instantly read that leftover "Enter" and skip your actual character input!
- The Fix: Put a space before the specifier:
scanf(" %c", &ch);. That leading space tells C: "Skip any whitespace and newlines before you start reading."
Reading Strings (Text)
For strings (character arrays), you do not use the &.
char name[50];
scanf("%s", name); // No & needed!
Why? Because in C, the name of an array acts as a pointer to its first element. It already is an address!
Limitations of scanf("%s", ...)
It stops reading at the very first space it encounters. If you type "Rahul Jangra", it only reads "Rahul". To read a full line with spaces, you should use fgets(), which we will cover in the Strings unit.
Input Failure: If a user types "hello" when you expect a number (%d),scanffails. The "hello" stays in the buffer, and your program might enter an infinite loop if you're not careful. Professional C code often uses custom input functions for better reliability.