C Input Validation
In this page:
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
#include <stdio.h>
int main() {
int x;
int result = sscanf("abc", "%d", &x);
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int x;
if (sscanf("42", "%d", &x) == 1) {
printf("%d", x);
} else {
printf("Invalid input");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int x;
if (sscanf("abc", "%d", &x) != 1) {
printf("Discarded invalid input");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
#include <stdlib.h>
int main() {
char line[20] = "42\n";
int value = strtol(line, NULL, 10);
printf("%d", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: