Course: CSE 1209 - Computer Fundamentals and Programming.
tags: cse-1209 c fundumental error
NOTE:
In
scanf, whitespace in the format string means:
“Skip any amount of whitespace in input (spaces, tabs, newlines)”
Whitespace = ' ', \n, \t
1. Space BEFORE a format specifier
scanf(" %d", &x);What the space does
- Skips all leading whitespace
- Then reads an integer
When you NEED it
- After previous input
- After reading a character
- After pressing Enter earlier
Example (important)
int x;
scanf(" %d", &x);Input:
42
✔ Works
2. Space BEFORE %c (VERY IMPORTANT)
scanf(" %c", &ch);Why this matters
%c does NOT skip whitespace by default
Bad:
scanf("%c", &ch);Input:
A↵
It may read:
'\n'
Good:
scanf(" %c", &ch);✔ Skips newline, then reads the character
👉 Rule:
Always put a space before
%cunless you explicitly want whitespace.
3. Space BETWEEN format specifiers
scanf("%d %d", &a, &b);What this means
- Read first integer
- Skip whitespace
- Read second integer
Input:
10 20
✔
Input:
10
20
✔
Input:
10 20
✔
4. What if I don’t put space?
scanf("%d%d", &a, &b);Surprise:
Still works.
Why?
%dalready skips leading whitespace- So space between
%dis optional
But:
👉 Readable code always uses space
5. Comma in format string (MOST COMMON MISTAKE)
scanf("%d, %d", &a, &b);This means:
Input MUST contain a comma
Input:
10, 20
✔
Input:
10 20
❌ FAILS
Key rule
Commas, letters, symbols in format string must appear EXACTLY in input
6. Literal characters in scanf
scanf("(%d)", &x);Input must be:
(25)
Otherwise → fail
7. Newline \n in scanf ❌ (TRAP)
scanf("%d\n", &x); // BADWhy it’s bad
-
\nmeans “skip whitespace” -
But
scanfwill WAIT for non-whitespace -
Program appears “stuck”
NEVER do this
scanf("%d\n", &x);
scanf("%d ", &x); // same problem8. %d vs %i (quick note)
scanf("%d", &x); // decimal only
scanf("%i", &x); // auto base (10, 8, 16)Input:
010 -> 8 (with %i)
0x10 -> 16
For beginners:
👉 Use %d
9. Mixed inputs (int + char) – classic bug
❌ Buggy code:
int x;
char ch;
scanf("%d", &x);
scanf("%c", &ch); // reads '\n'✅ Correct:
scanf("%d", &x);
scanf(" %c", &ch);10. Multiple inputs with characters
char ch1, ch2;
scanf(" %c %c", &ch1, &ch2);Input:
A B
✔
11. Always check return value (real fix)
if (scanf("%d %d", &a, &b) != 2) {
// input error
}This alone prevents half your bugs.
12. Golden rules (print & remember)
- Whitespace in format → skip whitespace
%d,%f,%sskip whitespace automatically%cdoes NOT → add space before it- Commas & symbols must exist in input
- Never use
\nat end ofscanf - Always check return value
scanfdoesn’t clear input buffer
Mental model (simple)
Think of scanf like this:
“I will match input EXACTLY as my format string says,
except that whitespace means ‘skip all whitespace’.”