A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
When scanf fails to match or leaves characters behind, they sit in the input buffer. The next read attempt hits the same stale characters and fails again. You get an infinite loop or a skipped input. The fix is to consume and discard characters until you hit a newline or EOF. The portable way is a loop calling getchar. The non-portable way is fflush(stdin), which works on some Windows compilers but is undefined behavior per the C standard. Do not use fflush on input streams.
#include <stdio.h>int main(void) {int age;char name[50];printf("Enter age: ");scanf("%d", &age);printf("Enter name: ");fgets(name, sizeof(name), stdin);printf("Age: %d, Name: \"%s\"\n", age, name);return 0;}
scanf read 25 and left the newline in the buffer. fgets immediately consumed that newline and returned an empty string. The name prompt appeared but fgets did not wait for input. The newline was already there. This is the classic scanf-then-fgets bug.
#include <stdio.h>void clear_input_buffer(void) {int ch;while ((ch = getchar()) != '\n' && ch != EOF) {/* discard */}}int main(void) {int age;char name[50];printf("Enter age: ");scanf("%d", &age);clear_input_buffer();printf("Enter name: ");fgets(name, sizeof(name), stdin);name[strcspn(name, "\n")] = '\0';printf("Age: %d, Name: \"%s\"\n", age, name);return 0;}
The clear_input_buffer function consumes everything up to and including the newline. After it runs, the buffer is empty. fgets waits for fresh input. The name is read correctly. This function is three lines. Put it in a utility header. Call it after every scanf that does not consume the full line.
fflush(stdin) is undefined behavior per the C standard. It works on MSVC and some Windows compilers, but it does not work on GCC on Linux or macOS. Code that uses fflush(stdin) is non-portable. Use the getchar loop. It works everywhere.
Input buffer management is a recurring annoyance in C. The getchar loop is the portable fix. The better long-term solution is to read entire lines with fgets and parse them with sscanf or strtol, avoiding the mixed scanf/fgets problem entirely. Next: size_t, the unsigned type that represents sizes and counts throughout the standard library.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.