Loading lessons...
Input Validation
Input Validation
Users type mistakes. A solid program checks its input before believing it.
Check the scanf return
scanf returns the number of items it successfully read:
int num;
if (scanf("%d", &num) == 1) {
printf("Got: %d", num);
} else {
printf("That wasn't a number!");
}
Range checks
Ask again if the value is out of range:
int age;
printf("Enter an age: ");
scanf("%d", &age);
while (age < 0 || age > 150) {
printf("That age is impossible!\n");
scanf("%d", &age);
}
Clearing bad input
If a scanf fails, the bad characters stay in the buffer. You may need to clean it up before the next read.
TL;DR
- Check scanf's return value to catch failures.
- Loop until input is in range.
- Bad reads leave junk in the buffer - clear it.
- Never trust user input.