C Input Validation
In this page:
if (scanf("%specifier", &variable_name) == 1) {
// input was valid
} else {
// input failed
}
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
int x;
// Declare result and set it to sscanf("abc", "%d", &x)
int result = sscanf("abc", "%d", &x);
// Print formatted text to the screen
printf("%d", result);
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
int x;
// Check whether sscanf("42", "%d", &x) == 1
if (sscanf("42", "%d", &x) == 1) {
// Print formatted text to the screen
printf("%d", x);
} else {
// Print formatted text to the screen
printf("Invalid input");
}
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
int x;
// Check whether sscanf("abc", "%d", &x) != 1
if (sscanf("abc", "%d", &x) != 1) {
// Print formatted text to the screen
printf("Discarded invalid input");
}
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
int choice;
sscanf("7", "%d", &choice);
// Check whether choice >= 1 && choice <= 5
if (choice >= 1 && choice <= 5) {
// Print formatted text to the screen
printf("Valid choice");
} else {
// Print formatted text to the screen
printf("Out of range");
}
// Return 0 to signal that the program finished successfully
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 standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
char line[20] = "42\n";
// Declare value and set it to strtol(line, NULL, 10)
int value = strtol(line, NULL, 10);
// Print formatted text to the screen
printf("%d", value);
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
- Ignoring the return value of
scanf, so bad input is treated as valid. - Not clearing the input buffer after a failed read, causing an infinite loop.
- Checking only that the read succeeded, and forgetting to check that the value is in the allowed range.
- Output in C is done with
printf(),puts(), newlines, and escape sequences that control how text appears. - Input is read with
scanf()andgets(), and format specifiers tell C how to interpret each value. - Input validation checks user data before your program relies on it.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: