Input Validation is the process of verifying that the data provided by a user or a file meets the expected criteria before the program processes it. In C, failing to validate input is a leading cause of security vulnerabilities and unexpected crashes.
The standard scanf() function is often risky. If a user enters a string when an integer is expected, scanf() fails, and the invalid input remains in the input buffer, often causing infinite loops or garbage data processing.
int variable.This is the simplest form of validation, ensuring a number falls within a specific logical boundary.
scanf() returns the number of items successfully scanned. Checking this value is the first line of defense against type mismatches.
Professional C developers often avoid scanf() for strings. Instead, they use fgets() to read an entire line safely and then parse it.
| Function | Why it's better |
|---|---|
fgets() |
Prevents buffer overflow by specifying the maximum size. |
sscanf() |
Parses data from a string rather than direct user input. |
isdigit() |
Checks character-by-character if the input is a numeric digit. |
When validation fails, you must clear the "trash" left in the buffer, or the next input request will automatically read that same trash.
\n) from the input.fgets() and atoi() or strtol() is much safer than a raw scanf()!