Explain it simply
Explain it simply
Data from the keyboard is not a number; it is a queue of characters the user typed. Type "20" and press Enter, and the program receives three characters: '2', '0' and a newline ('\n'). To use it as a number, you have to convert it yourself and check that it made sense.
The user might type "twenty", press Enter on an empty line, paste a huge line, or close the input without typing anything. So treat input like a parcel from a stranger: inspect it before you open it.
Problem → Why → Solution
The problem: typing "abc" sends the program haywire
The program below is meant to keep asking until it gets an age between 0 and 130. Typing 20 works perfectly. Typing "abc" makes "Enter your age: " repeat endlessly without ever letting you type again. A version without the loop would instead print whatever garbage happens to be in age.
#include <stdio.h>
int main(void) {
int age = -1;
while (age < 0 || age > 130) {
printf("Enter your age: ");
scanf("%d", &age); /* return value ignored */
}
printf("You are %d years old.\n", age);
return 0;
}Why does the loop never end?
scanf("%d") stops at the 'a' and returns 0, meaning zero successful conversions. The "abc" is never consumed and stays in the input buffer, so on the next pass scanf hits the same 'a' again, and age never changes. Only checking the return value and discarding the bad line breaks the cycle.
Core concept: read a line, then check and convert
A terminal collects input line by line and hands it over only when the user presses Enter, and the newline itself is part of that input. The end of input is called EOF (end of file); a user sends it with Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows. When input is redirected from a file, EOF arrives when the file ends.
scanf("%d", &age) needs the address &age because it writes the result into your variable. It returns the number of successful conversions: 1 for success, 0 when the text did not start with a number (and the bad characters stay in the buffer), or EOF when input ran out. On 0 or EOF it never touches age, so an uninitialised age holds garbage. Reading a number too big for an int with %d is undefined behaviour under the standard, and scanf also leaves the newline after the number sitting in the buffer.
The sturdier approach splits the job in two. First read the whole line with fgets(buf, sizeof buf, stdin); it never writes more than sizeof buf - 1 characters, always adds the terminating '\0', and returns NULL on EOF or error. A line with no '\n' in it was longer than the buffer. Then convert with strtol(buf, &end, 10): end == buf means there were no digits at all, a non-space character after end means trailing junk such as "12abc", and errno == ERANGE means the value does not fit in a long. Finally check the range your program needs.
The old gets(buf) never received the buffer size, so a long line simply overwrote the memory beyond the buffer. There is no way to use it safely, so C11 removed it from the language, and fgets() is its replacement.
- fgets: a line, or EOF?
- Does it contain '\n' (or was it too long)?
- strtol: any digits? anything left over?
- Check ERANGE and the min..max range
Use the value only after it has passed all four checkpoints.
General pattern
char buf[SIZE];
if (fgets(buf, sizeof buf, stdin) == NULL) {
/* EOF or read error: stop or use a default */
}
char *end;
errno = 0;
long value = strtol(buf, &end, 10);
/* reject if: end == buf, junk after end, errno == ERANGE,
or value outside [min, max] */fgets reads one line within the buffer's size, and strtol converts it while also reporting where it stopped (end). Reject the input if any of the four checks fails.
Example: validating typed lines
Instead of waiting for the keyboard, this example feeds parse_int() seven prepared lines shaped exactly as fgets() would deliver them, '\n' included. The output is identical on every run, and you see all the typical typing mistakes at once. The deeper section shows the same check wired to the real keyboard.
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Parses a whole line as an int in [min, max].
Returns NULL on success, or a message saying what is wrong. */
const char *parse_int(const char *line, int min, int max, int *out) {
char *end;
errno = 0;
long value = strtol(line, &end, 10);
if (end == line) {
return "not a number";
}
while (isspace((unsigned char)*end)) {
end++; /* allow trailing spaces and '\n' */
}
if (*end != '\0') {
return "extra characters after the number";
}
if (errno == ERANGE || value < min || value > max) {
return "out of range";
}
*out = (int)value;
return NULL;
}
int main(void) {
/* Lines exactly as fgets() would hand them over, '\n' included. */
const char *lines[] = {"20\n", " 35\n", "abc\n", "12abc\n",
"150\n", "\n", "99999999999999999999\n"};
int count = (int)(sizeof lines / sizeof lines[0]);
for (int i = 0; i < count; i++) {
int age;
int shown = (int)strcspn(lines[i], "\n"); /* length before '\n' */
const char *problem = parse_int(lines[i], 0, 130, &age);
if (problem == NULL) {
printf("\"%.*s\" -> age %d\n", shown, lines[i], age);
} else {
printf("\"%.*s\" -> rejected: %s\n", shown, lines[i], problem);
}
}
return 0;
}Code breakdown
- Convert and remember where it stopped
long value = strtol(line, &end, 10);strtol skips leading spaces, converts the digits to a long and stores in end the address of the first character it could not use. The 10 means decimal. errno is reset to 0 just before the call.
- No digits at all
if (end == line) {If end never moved, no digits were found, as with "abc" and the empty line. strtol returns 0 in that case, so without this check "abc" would be accepted as age 0.
- Trailing junk
if (*end != '\0') {If, after skipping spaces and the '\n', we are not at the end of the string, something like "12abc" has leftovers. scanf("%d") would quietly accept that line as 12.
- Overflow and range
if (errno == ERANGE || value < min || value > max) {For numbers that are too large, strtol sets errno to ERANGE. long is 32 bits on Windows and 64 bits on 64-bit Linux, but thanks to these two checks both platforms report "out of range".
- Showing the line without its newline
int shown = (int)strcspn(lines[i], "\n"); /* length before '\n' */strcspn counts the characters before the '\n', and %.*s prints only that many. The same function is the usual way to strip fgets' newline: line[strcspn(line, "\n")] = '\0';.
"20" -> age 20
" 35" -> age 35
"abc" -> rejected: not a number
"12abc" -> rejected: extra characters after the number
"150" -> rejected: out of range
"" -> rejected: not a number
"99999999999999999999" -> rejected: out of rangeReading from the real keyboard
The program below really reads from stdin. Run it in a terminal and it shows the prompt and waits. Run it with no input at all (for example ./age < /dev/null) and fgets returns NULL at once, so the program ends politely. The prompt has no newline, so fflush(stdout) makes sure it appears before the program waits.
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char line[32];
printf("Enter your age: ");
fflush(stdout); /* show the prompt before waiting */
if (fgets(line, sizeof line, stdin) == NULL) {
printf("\nNo input (end of file), nothing to do.\n");
return 0;
}
if (strchr(line, '\n') == NULL && !feof(stdin)) {
int c; /* line too long: drain the rest */
while ((c = getchar()) != '\n' && c != EOF) {
}
printf("That line is too long.\n");
return 0;
}
char *end;
errno = 0;
long age = strtol(line, &end, 10);
int no_digits = (end == line);
while (isspace((unsigned char)*end)) {
end++;
}
if (no_digits || *end != '\0' || errno == ERANGE || age < 0 || age > 130) {
printf("Please type a whole number from 0 to 130.\n");
return 0;
}
printf("You are %ld years old.\n", age);
return 0;
}The rest of an overlong line
When a line does not fit in the buffer, its remaining characters stay in stdin and would arrive as a "new line" on the next fgets call. The getchar() loop eats them up to the '\n' or EOF.
scanf, fgets + strtol and gets compared
| Approach | Strength | Watch out for |
|---|---|---|
| scanf("%d", &n) | Short to write | Garbage if unchecked, accepts "12abc" as 12, leaves '\n' |
| fgets + strtol | Checks the whole line, reports overflow via ERANGE | More code; you handle the '\n' yourself |
| gets(buf) | None | Removed in C11; cannot prevent buffer overflow |
Toolchains push back on gets as well. MinGW-w64 GCC 16 with -std=c17 warns "Using gets() is always unsafe - use fgets() instead", and glibc on Linux no longer declares gets at all in C11 and later modes.
In real projects
Where this shows up in real projects
Command-line tools read menu choices, port numbers and config values with the fgets + strtol pattern, and when the input is wrong they say exactly what is wrong and ask again. Since input may come from a file or a pipe (./tool < answers.txt), handling EOF properly is what keeps automation scripts from hanging forever.
From a security angle, input code that ignores buffer sizes, such as gets() or scanf("%s") without a width, is the first place attackers look. The 1988 Morris worm famously spread by overflowing a gets() call in the fingerd program. Code reviews for embedded devices and servers routinely demand that every input is checked for length, format and range before use.
Common mistakes
Common mistakes
1. Ignoring scanf()'s return value
Typing "abc" makes scanf return 0 without touching the variable, and Ctrl+D or Ctrl+Z makes it return EOF. Try it with int age = 7; and age is still 7 after either failure. Check if (scanf("%d", &age) != 1) { ... } and discard the bad line, or better, switch to fgets + strtol.
2. Forgetting the & in scanf
scanf("%d", age) uses the value of age as an address and can crash the program. With -Wall, GCC reports "format '%d' expects argument of type 'int *', but argument 2 has type 'int'". Never ignore that warning.
3. Reading a string with an unbounded %s
char name[20]; scanf("%s", name); writes past the buffer as soon as someone types 20 or more characters, and -Wall does not warn about it. Give a width, scanf("%19s", name), leaving one byte for the terminator, or use fgets instead.
4. Mixing scanf and fgets
scanf("%d", &age) leaves the '\n' after the number in the buffer, so the next fgets(name, ...) immediately returns an empty line and the user never gets to type a name. Using fgets for all input and parsing each line is the simplest cure.
Best practices
Best practices
- Read input line by line with fgets, convert with strtol or strtod, and apply all four checks.
- Keep parsing in its own function such as parse_int() and test it with plain strings.
- Call fflush(stdout) after a prompt, and stop gracefully on EOF.
- Tell the user precisely what was wrong: not a number, or out of range.
Mini challenge
Mini challenge: validating an order line
Parse a line of the form "quantity price", such as "3 4.50", by chaining strtol and strtod, then print the total for valid lines and "rejected" for the rest.
- int parse_order(const char *line, long *quantity, double *price) returns 1 on success and 0 otherwise
- Quantity must be 1 to 100; price must be above 0 and at most 10000
- Start strtod where strtol stopped, and reject anything other than spaces left at the end
- Test it with six fgets-style lines: {"3 4.50\n", "2 0.99\n", "three 4.50\n", "3\n", "3 4.50 extra\n", "0 4.50\n"}
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Parses "quantity price", e.g. "3 4.50". Returns 1 on success. */
int parse_order(const char *line, long *quantity, double *price) {
// TODO: strtol for the quantity; check digits, ERANGE, 1..100
// TODO: strtod from where strtol stopped; check digits, ERANGE, range
// TODO: skip trailing spaces; anything else left means reject
// TODO: store the results through the pointers
return 0;
}
int main(void) {
// TODO: an array with the six test lines from the requirements
// TODO: for each line print "total %.2f" or "rejected"
return 0;
}Expected: The program prints: 3 4.50 total 13.50 2 0.99 total 1.98 three 4.50 rejected 3 rejected 3 4.50 extra rejected 0 4.50 rejected
Show hint
After strtol, keep end in const char *rest and call strtod(rest, &end). If end == rest, the price is missing, as in the line "3". To line up the columns, printf("%-14.*s", shown, line) works well.
Show solution
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Parses "quantity price", e.g. "3 4.50". Returns 1 on success. */
int parse_order(const char *line, long *quantity, double *price) {
char *end;
errno = 0;
long q = strtol(line, &end, 10);
if (end == line || errno == ERANGE || q < 1 || q > 100) {
return 0;
}
const char *rest = end;
errno = 0;
double p = strtod(rest, &end);
if (end == rest || errno == ERANGE || p <= 0.0 || p > 10000.0) {
return 0;
}
while (isspace((unsigned char)*end)) {
end++;
}
if (*end != '\0') {
return 0; /* something left over */
}
*quantity = q;
*price = p;
return 1;
}
int main(void) {
const char *lines[] = {"3 4.50\n", "2 0.99\n", "three 4.50\n",
"3\n", "3 4.50 extra\n", "0 4.50\n"};
int count = (int)(sizeof lines / sizeof lines[0]);
for (int i = 0; i < count; i++) {
long quantity;
double price;
int shown = (int)strcspn(lines[i], "\n");
if (parse_order(lines[i], &quantity, &price)) {
printf("%-14.*s total %.2f\n", shown, lines[i], quantity * price);
} else {
printf("%-14.*s rejected\n", shown, lines[i]);
}
}
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Keyboard input is text with a trailing newline that may also end in EOF, so treat it as untrusted data.
- scanf() returns the number of successful conversions (or EOF); ignoring it leads to garbage values and endless loops.
- The standard pattern is fgets(buf, sizeof buf, stdin), then strtol with checks on end, errno and the range.
- C11 removed gets(); fgets(), which takes the buffer size, replaces it.
GNU C compiler diagnostics — GNU Project