Lesson 109 +10 XP

Input Validation in Depth

Robust programs validate input everywhere: scanf return, range, buffer size.

Validate scanf results


c
int result = scanf("%d", &num) == 1;
if (result == 0) {
    printf("Invalid input.");
}

Clear the buffer after failure


c
while (getchar() != '
');

Flushes the bad characters.

Read to the line with a size limit


c
fgets(line, sizeof(line), stdin);

safe against overruns.

Final shape

  1. Get data.
  1. Check the get was successful.
  1. Validate range/type.
  1. 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.