Validating input
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Never trust input: a user (or an attacker) can enter anything.
scanf returns the number of values it read successfully. This is the first line of defence:
int n;
if (scanf("%d", &n) != 1) {
printf("A number is needed\n");
return 1;
}
A trap: if abc was entered, scanf("%d") doesn't take these characters from the input. The next call sees abc again, and the loop never ends. The garbage has to be thrown away by hand:
int c;
while ((c = getchar()) != '\n' && c != EOF)
; // skip the rest of the line
It's more reliable to read the whole line with fgets and parse it afterwards with sscanf or strtol. That way garbage never gets stuck in the input:
char line[64];
while (fgets(line, sizeof line, stdin)) {
int n;
if (sscanf(line, "%d", &n) == 1 && n > 0) { ... }
}
Check not only the format but also the meaning: an age can't be negative, and an index must be less than the size of the array.
Task. The program reads lines until it meets a valid number from 1 to 10. For each wrong line it prints invalid, and for the right one it prints ok N and ends.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.