C Programming • C17 baseline, standards-specific features labeled
Read and Validate Console Input
Read a complete line, convert it deliberately, and reject malformed or out-of-range input.
Input is not valid merely because it came from a terminal. fgets limits how many characters are read into a buffer. strtol reports where conversion stopped and can signal range errors, which lets the program distinguish a valid integer from extra text.
Example
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char line[64];
char *end = NULL;
if (fgets(line, sizeof line, stdin) == NULL) {
fputs("Input could not be read.\n", stderr);
return 1;
}
errno = 0;
long value = strtol(line, &end, 10);
if (end == line || errno == ERANGE) {
fputs("Enter a valid integer.\n", stderr);
return 1;
}
while (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r') {
++end;
}
if (*end != '\0') {
fputs("Unexpected characters after the integer.\n", stderr);
return 1;
}
printf("Value: %ld\n", value);
return 0;
}
What to expect
For input 42, the program prints Value: 42. Inputs with trailing non-whitespace characters are rejected.
Key idea: Bound the read and check the conversion result; never assume input is well-formed.