Loading lessons...
Input Validation in Depth
Input Validation, Robustness
Robust programs validate input everywhere: scanf return, range, buffer size.
Validate scanf results
int result = scanf("%d", &num) == 1;
if (result == 0) {
printf("Invalid input.");
}
Clear the buffer after failure
while (getchar() != '\n');
Flushes the bad characters.
Read to the line with a size limit
fgets(line, sizeof(line), stdin);
safe against overruns.
Final shape
- Get data.
- Check the get was successful.
- Validate range/type.
- Else, clear and ask again.
TL;DR
- Check scanf's return value.
- Clear leftover input after a failed read.
- Use fgets + size to cap reads.
- Loop until input is valid.