Common scanf() Problems and Fixes
Almost every C student meets this bug: you write two scanf calls, run the program, and it skips the second input without waiting for you. It feels like magic, but there is a simple reason.
In this lesson you will learn why it happens (the leftover Enter key) and the easy fixes for the 4 most common scanf problems.
What You Will Learn
- What the input buffer is.
- Why
scanf("%c")skips input after reading a number. - How a space before
%cfixes it. - Why
fgetsafterscanfreads an empty line, and the fix. - How to handle wrong input (letters instead of numbers).
Common scanf() Problems Explained
Exam definition: scanf "skips" input because the newline character ('\n') from the Enter key stays in the input buffer. A following scanf("%c"), getchar() or fgets() reads that leftover newline instead of waiting for new input.
The input buffer
- When you type
5and press Enter, the buffer holds two characters:'5'and'\n'. scanf("%d")takes the5but leaves the'\n'in the buffer.%d,%fand%sautomatically skip spaces and newlines before the value, so they are not affected.%c,getchar()andfgets()do not skip. They happily read the leftover'\n'.
Memory trick: Think of the buffer as a plate. scanf("%d") eats the number but leaves the Enter crumb on the plate. %c eats the crumb. Fix: clean the plate first (a space before %c).
The 4 common problems and fixes
| Problem | Cause | Fix |
|---|---|---|
%c after %d is skipped | It reads the leftover '\n' | Use scanf(" %c", &ch); (space before %c) |
fgets after scanf gets an empty line | It reads the leftover '\n' | Clear the rest of the line first (see Example 2) |
%s reads only the first word | %s stops at a space | Use fgets() for full lines |
Letters typed for %d | scanf fails, returns 0, the letters stay in the buffer | Check the return value; clear the buffer |
Syntax of the Fixes
scanf(" %c", &ch); /* space skips leftover spaces and newlines */
int c;
while ((c = getchar()) != '\n' && c != EOF) { } /* clear the rest of the line */
if (scanf("%d", &n) != 1) { /* the input was not a number */ }
Example 1: The Bug, %c Reads the Leftover Enter
#include <stdio.h>
int main(void)
{
int number;
char letter;
printf("Enter a number: ");
scanf("%d", &number);
printf("Enter a letter: ");
scanf("%c", &letter); /* BUG: reads the leftover '\n' */
printf("Number = %d, letter code = %d\n", number, letter);
return 0;
}
Output
Enter a number: 5 Enter a letter: Number = 5, letter code = 10
Code Explanation
- The user types
5and presses Enter. The buffer holds'5'and'\n'. scanf("%d")reads 5. The'\n'is left behind.scanf("%c")finds'\n'waiting and reads it immediately. It never waits for the user.- The letter code printed is 10, which is the ASCII code of
'\n'. That proves the newline was read.
The fix: change scanf("%c", &letter); to scanf(" %c", &letter);. The space tells scanf to skip any spaces and newlines first.
How the Fix Works
- A space in scanf's format means "skip all whitespace (spaces, tabs, newlines) here".
- So
" %c"first throws away the leftover'\n', then waits for a real character. - For
fgets, there is no such shortcut, so we read and throw away characters withgetchar()until we reach the'\n'.
Example 2: scanf Then fgets, With the Fix
#include <stdio.h>
#include <string.h>
int main(void)
{
int age;
char name[50];
int c;
printf("Enter your age: ");
scanf("%d", &age);
while ((c = getchar()) != '\n' && c != EOF) { } /* clear the leftover line */
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
printf("%s is %d years old.\n", name, age);
return 0;
}
Output
Enter your age: 21 Enter your full name: Riya Sharma Riya Sharma is 21 years old.
Without the while line, fgets would read the empty leftover line, and name would be empty.
Important Points to Remember
- The skip happens because Enter (
'\n') stays in the buffer. %d,%f,%sskip whitespace;%c,getchar,fgetsdo not.- Fix for chars:
scanf(" %c", &ch); - Fix before fgets: clear the rest of the line with a getchar loop.
- Check scanf's return value to catch wrong input.
Common Mistakes When Fixing scanf
| Mistake | Why it is wrong | Better way |
|---|---|---|
fflush(stdin); | Undefined behaviour in standard C; works only on some compilers | Use the getchar loop |
scanf("%d\n", &n); | Waits for extra non-space input after Enter | Never put \n in the format |
Calling getchar() once to "eat" the newline | Fails if the user typed extra spaces | Loop until '\n' |
| Ignoring scanf's return value | Wrong input goes unnoticed | if (scanf("%d", &n) != 1) |
scanf Problems Practice Questions
- Why does
scanf("%c")skip input afterscanf("%d")? - How does a space before
%cfix the problem? - Why is
fflush(stdin)not a good fix? - What does scanf return if the user types "hello" for
%d? - Which format specifiers skip leading whitespace automatically?
Show answers
- Because the newline from the Enter key stays in the input buffer, and
%creads it. - A space in the format skips all whitespace, including the leftover newline, before reading the character.
fflushis defined only for output streams; using it onstdinis undefined behaviour.- 0, because no value could be read.
%d,%f,%s(and most others except%cand%[).
Coding Exercise
Ask for a product quantity (int) and then a size letter (S, M or L). Make sure the size is not skipped. Print both.
Show solution
#include <stdio.h>
int main(void)
{
int qty;
char size;
printf("Quantity: ");
scanf("%d", &qty);
printf("Size (S/M/L): ");
scanf(" %c", &size); /* space fixes the skip */
printf("Order: %d shirts, size %c\n", qty, size);
return 0;
}
Quantity: 3 Size (S/M/L): M Order: 3 shirts, size M
Quick Quiz: scanf Problems (MCQ)
-
What is left in the buffer after
scanf("%d")reads "7" + Enter?A) Nothing B)
'7'C)'\n'D)'\0' -
Which reads a character and skips the leftover newline?
A)
scanf("%c", &c);B)scanf(" %c", &c);C)scanf("%c ", c);D)getchar(c); -
scanf("%s", name)with input "Riya Sharma" stores:A) Riya Sharma B) Riya C) Sharma D) Nothing
-
The ASCII code of
'\n'is:A) 0 B) 10 C) 13 D) 32
-
Which is NOT a portable way to clear stdin?
A) A getchar loop until
'\n'B)fflush(stdin)C)scanf(" %c")before a char D) Reading the line with fgets
Show answers
- C: the newline.
- B:
scanf(" %c", &c); - B: Riya (
%sstops at a space). - B: 10.
- B:
fflush(stdin)
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Cause of skipping | Leftover '\n' in the input buffer |
|---|---|
| Skip whitespace | %d, %f, %s |
| Don't skip | %c, getchar(), fgets() |
| Fix for %c | scanf(" %c", &ch); |
| Fix before fgets | getchar loop until '\n' |
| fflush(stdin) | Undefined behaviour; avoid |
ASCII of '\n' | 10 |
Frequently asked questions
- Why does scanf skip the next input?
- The Enter key's newline stays in the buffer and is read by the next
%c, getchar or fgets. - How do you fix scanf skipping a character input?
- Put a space before %c:
scanf(" %c", &ch); - Why not use fflush(stdin)?
- It is undefined behaviour in standard C; it only works on some compilers.
- How do you detect wrong input in scanf?
- Check the return value:
scanf("%d", &n) != 1means it failed.
Remember
- scanf leaves the Enter crumb on the plate; clean it before
%cor fgets. - Magic fix: space before
%c.
Next Topic
Next lesson: Operators in C. Module 04 starts with operators: the symbols C uses to calculate and compare.