← Back to C Course | Chapter 2: Input & Output | Lesson 7 of 7

C Input Validation

Why Unchecked scanf Is Dangerous

scanf returns the number of items it successfully read, but that return value is easy to ignore -- if a user types letters where a number is expected, the read fails, the target variable is left with whatever garbage it had before, and the program keeps running on bad data.

Example: Why Unchecked scanf Is Dangerous

c
#include <stdio.h>
int main() {
	int x;
	int result = sscanf("abc", "%d", &x);
	printf("%d", result);
	return 0;
}

Checking the Return Value

Comparing scanf's return value against the number of conversions you requested -- if (scanf("%d", &x) == 1) -- is the first line of defense, letting you detect a failed read immediately instead of silently trusting an uninitialized variable.

Example: Checking the Return Value

c
#include <stdio.h>
int main() {
	int x;
	if (sscanf("42", "%d", &x) == 1) {
		printf("%d", x);
	} else {
		printf("Invalid input");
	}
	return 0;
}

Clearing the Input Buffer

When scanf fails to match a number, the invalid characters are left sitting in the input buffer and will immediately cause the next read to fail too, so a failed scan should be followed by discarding characters up to the next newline before retrying.

Example: Clearing the Input Buffer

c
#include <stdio.h>
int main() {
	int x;
	if (sscanf("abc", "%d", &x) != 1) {
		printf("Discarded invalid input");
	}
	return 0;
}

Validating Ranges After a Successful Read

A successful scanf only confirms the input had the right format, not that the value makes sense -- a menu that reads an option number still needs a separate range check to reject an out-of-bounds choice like 99 on a 5-item menu.

Example: Validating Ranges After a Successful Read

c
#include <stdio.h>
int main() {
	int choice;
	sscanf("7", "%d", &choice);
	if (choice >= 1 && choice <= 5) {
		printf("Valid choice");
	} else {
		printf("Out of range");
	}
	return 0;
}

Safer Alternatives for Line-Based Input

Reading a whole line with fgets into a buffer and then parsing it explicitly (with sscanf or strtol) gives you more control than scanf alone, since you can inspect the raw input before deciding how to interpret it, and it naturally avoids scanf's dangling-buffer problem.

Example: Safer Alternatives for Line-Based Input

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	char line[20] = "42\n";
	int value = strtol(line, NULL, 10);
	printf("%d", value);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.