Lesson 5: scanf — Read keyboard input

Read user input into variables with scanf. Learn why & matters, the %lf gotcha, and the typical bugs.

📖 What to learn on this page
✅ Must-know essentials
  • scanf("%d", &x); reads into a variable
  • Always put & before the variable
  • double uses %lf (not %f!)
  • Don't put extra characters in the format string
⭐ Read if you have time
  • Check scanf's return value for errors
  • Whitespace skipping rules
  • Leftover-input problems and fixes
  • For strings, prefer fgets (safer)
💪 Not getting it on the first try? That's normal.
scanf trips up beginners on two points: "&" and "%lf". Both are concepts that carry over into pointers later, so for now it's fine to just memorize them as "rules".
Stumbling points
  1. & signals that you're passing the variable's "address" — covered in detail later in Pointers
  2. The format for double is %lf (scanf only; printf is fine with %f)
  3. Spaces or Enter typed between inputs are skipped automatically by the numeric formats
  4. Strange behavior = something extra in the format string, or a forgotten &
💡 Tip: 9 times out of 10, an error comes from a forgotten "&" or a missing "%lf". Suspect these two first.

scanf basics — the flip side of printf

If printf sends text to the screen, scanf reads input from the keyboard. They're mirror images of each other.
📤 printf (output)
printf("%d\n", a);
// print variable a to screen
📥 scanf (input)
scanf("%d", &a);
// read from keyboard into variable a

The standard pattern

int a;
printf("Enter a: ");   // prompt
scanf("%d", &a);       // read input
printf("a = %d\n", a);
Flow: ① prompt with printf → ② read with scanf → ③ use the value. This three-step pattern is the bread and butter of console I/O.

⚠️ Why & (ampersand) is required

The number-one rule of scanf: put & in front of every variable. Forgetting it usually crashes the program.
🔴 What happens if you forget &
int a;
scanf("%d", a);    // ❌ forgot &
What happens:
• The compiler emits a warning (take warnings seriously!)
• Running the program almost always results in a segmentation fault (crash)
• Worst case: it writes into some unrelated memory region, causing a subtle bug that's hard to track down

What & actually is: the variable's "address"

The variable a holds a value. &a is the memory address where a lives.
a = the contents of the box (the value)
&a = the location of the box (the address)

scanf needs to know where to put the new value,
so we hand it the address (&a).
💡 Rule of thumb: always prefix scanf variables with &, and never prefix printf's. (printf just reads the value — it doesn't need an address.) The full mechanics are covered in Pointer Basics.

Exception: strings (arrays)

char name[50];
scanf("%s", name);   // ← no & for array name
Why: an array name is already an address (that's a special C rule). For now, just remember: "arrays are the exception."

🧩 The %lf puzzle — scanning a double

In scanf, double uses %lf. That's different from printf, and it's a classic source of confusion.
Typescanf specifierprintf specifier
int%d%d
float%f%f
double%lf ⚠️%f (%lf also OK)
char%c%c
string%s%s
🔴 Common mistake: %f for a double
double b;
scanf("%f", &b);    // ❌ double needs %lf
Result: b ends up with a completely wrong value (often 0.0, or something huge). It's undefined behavior. Compile with -Wall to catch these.
Mnemonic: scanf + double → use %lf (the l stands for "long"). Only scanf is picky about this.

scanf simulator

Type a value and press Enter to see how scanf would store it.
Enter a:
variable a
(empty)
printf("%d", a)
—

Common pitfalls

Pitfall ① missing &
scanf("%d", &a);
Leaving off & will usually crash the program
Pitfall ② %f for double
scanf("%lf", &b);
In scanf, double needs %lf
Pitfall ③ extra chars
scanf("%d\n", &a); ← don't add \n
scanf("Enter %d", &a); ← don't embed prose
Pitfall ④ consecutive scanfs
Leftover newlines can bite you when mixing %c with other specifiers.

✅ Safe template

int a;
double b;

printf("Enter int: ");
scanf("%d", &a);

printf("Enter double: ");
scanf("%lf", &b);  // lf!

printf("a=%d, b=%f\n", a, b);

💡 Bonus: check the return value

scanf returns the number of items it successfully read, which is handy for catching bad input.
int a;
if (scanf("%d", &a) != 1) {
    printf("Please enter an integer\n");
    return 1;
}
For real-world input handling, prefer fgets + sscanf. See Safe String Handling.

Try it yourself — scanf

The browser simulator swaps in a prompt dialog wherever scanf would normally read from the keyboard.
scanf_demo.c
Output
Press "Run" to execute...
💡 A few things to try

Related Lessons

Getting Started
printf
Printing values to the screen with format specifiers.
Advanced
Pointer Basics
What & really does: addresses and pointers.
Advanced topics
Safe String Handling
Safer alternatives: fgets + sscanf.
Practice problems for this lessonVariables, operators & I/O: 13 practice problemsWrite code in your browser and get it checked automatically. Hints and solutions included →
← Previous lesson
Lesson 4: printf & scanf
Next lesson →
Lesson 6: Quiz (Variables & printf)

Review Quiz

Check your understanding of this lesson!

Q1. Which is the correct way to read an integer into int x;?

scanf("%d", &x);
scanf("%d", x);
scanf(x, "%d");

scanf needs the address where it should write the value, so prefix the variable name with &.

Q2. Why is & needed on scanf arguments?

To pass the variable's address so scanf can write into it
So the function can return a pointer
To treat the value as a string

scanf updates the caller's variable, so it needs a pointer (an address) rather than the value itself.

Q3. Which is correct for reading a string into char name[50];?

scanf("%s", name);
scanf("%s", &name);
scanf("%c", name);

Array names decay to the address of their first element, so & isn't needed. %s reads a single word up to whitespace.