Lesson 109 +10 XP

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

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