r/cprogramming • u/PrimeEmre • 5h ago
Why your C program loops forever when you type a letter, and how to read input safely
A question that comes up a lot: "I used scanf("%d", &x) and when I type abc my program spins forever."
Why it happens: when scanf can't parse the input as a number, it doesn't consume it. abc stays in the input buffer, the next scanf fails on the same characters, and so on forever.
The fix: check the return value (the number of items read successfully), and throw away the bad line when it fails:
c
int age;
printf("Enter your age: ");
while (scanf("%d", &age) != 1) {
int c;
while ((c = getchar()) != '\n' && c != EOF) { } /* discard the bad input */
if (c == EOF) return 1;
printf("That's not a number. Try again: ");
}
A few other input traps worth knowing:
- Strings with spaces:
scanf("%s")stops at the first space. Usefgets(buf, sizeof buf, stdin), which also can't overflow the buffer. - fgets keeps the newline: strip it with
buf[strcspn(buf, "\n")] = '\0'; - Never use
gets(): it was removed in C11 because it has no length limit. - Missing
&:scanf("%d", age)passes a value where an address is expected, which is undefined behavior and usually a crash.
I wrote this up in more detail for beginners, with a worked example and a section on using the input with if/else (including the classic if (x = 5) bug): https://blog.emreguzel.ca/2026/09/29/user-input-in-c-a-complete-guide-for-beginners/