Reading user input is where many C programs go wrong. scanf("%s", buf) can write past the end of buf if the user types too much, scanf("%d", &n) leaves bad input stuck in the buffer, and the old gets function was so unsafe it was removed from the language. The reliable pattern is to read a whole line with fgets, which never writes more than you allow, and then convert it with strtol or sscanf, checking every step.
In this lesson you will learn
- Reading a line safely with
fgets - Removing the trailing newline with
strcspn - Detecting and discarding lines that are too long
- Converting text to a number with full error checking
- Why
scanfleaves bad input behind
You should know basic input and output, strings and string-to-number conversion.
Reading Lines with fgets
A real program passes stdin to fgets. These examples write the “typed” text into a temporary file created with tmpfile() and read from that instead, so the input is visible and the output repeatable. fgets behaves the same either way.
#include <stdio.h>
#include <string.h>
/* Pretend keyboard: in a real program, read from stdin instead of `in` */
static FILE *fake_input(const char *text) {
FILE *f = tmpfile();
if (f == NULL) return NULL;
fputs(text, f);
rewind(f);
return f;
}
int main(void) {
FILE *in = fake_input("Nusrat Jahan\nA very long line that does not fit in the buffer\nok\n");
if (in == NULL) return 1;
char name[32];
if (fgets(name, sizeof name, in) != NULL) { /* reads at most 31 chars + '\0' */
printf("raw: [%s]\n", name); /* keeps the '\n' */
name[strcspn(name, "\n")] = '\0'; /* strip the newline */
printf("clean: [%s]\n", name);
}
char small[10];
if (fgets(small, sizeof small, in) == NULL) return 1; /* only part of the long line fits */
printf("partial: [%s]\n", small);
if (strchr(small, '\n') == NULL) { /* no newline: line was cut short */
int c;
while ((c = fgetc(in)) != '\n' && c != EOF) /* discard the rest of the line */
;
printf("rest of the long line discarded\n");
}
if (fgets(small, sizeof small, in) == NULL) return 1;
small[strcspn(small, "\n")] = '\0';
printf("next line: [%s]\n", small);
printf("at end of input, fgets returns %s\n", fgets(small, sizeof small, in) ? "text" : "NULL");
fclose(in);
return 0;
}
Output
raw: [Nusrat Jahan
]
clean: [Nusrat Jahan]
partial: [A very lo]
rest of the long line discarded
next line: [ok]
at end of input, fgets returns NULL
fgets(buf, size, stream)reads up tosize - 1characters, stopping after a newline, and always adds'\0'. Passingsizeof namemeans it can never overflow the array.- The newline is kept, as the
rawoutput shows.name[strcspn(name, "\n")] = '\0'removes it;strcspnreturns the position of the first newline, or the string’s length if there is none, so the line is safe either way. - When a line is longer than the buffer,
fgetsreturns only the first part (9 characters for the 10-byte buffer). The missing newline tells you the line was cut, and the loop withfgetcthrows away the rest so it does not appear as the next “line”. fgetsreturnsNULLat the end of input or on an error. Always check the return value before using the buffer.
Validating Numbers
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Read one line and convert it to an int; returns 1 on success */
static int read_int(FILE *in, int *out) {
char line[64];
if (fgets(line, sizeof line, in) == NULL) return 0;
char *end;
errno = 0;
long v = strtol(line, &end, 10);
if (end == line) return 0; /* no digits at all */
while (*end == ' ' || *end == '\t') end++;
if (*end != '\n' && *end != '\0') return 0; /* junk after the number */
if (errno == ERANGE || v < INT_MIN || v > INT_MAX) return 0;
*out = (int)v;
return 1;
}
int main(void) {
FILE *in = tmpfile();
if (in == NULL) return 1;
fputs("42\n12abc\n\n99999999999\n-7\nhello\n", in);
rewind(in);
for (int i = 0; i < 6; i++) {
int v;
if (read_int(in, &v)) printf("line %d: valid number %d\n", i + 1, v);
else printf("line %d: invalid, please try again\n", i + 1);
}
fclose(in);
/* For comparison: scanf stops at the first bad character and leaves it unread */
FILE *in2 = tmpfile();
if (in2 == NULL) return 1;
fputs("42 abc 7\n", in2);
rewind(in2);
int a = 0, b = 0;
int got = fscanf(in2, "%d %d", &a, &b);
printf("fscanf matched %d value(s): a=%d, b=%d (unchanged)\n", got, a, b);
int c = fgetc(in2);
while (c == ' ') c = fgetc(in2);
printf("next unread character: '%c'\n", c);
fclose(in2);
return 0;
}
Output
line 1: valid number 42
line 2: invalid, please try again
line 3: invalid, please try again
line 4: invalid, please try again
line 5: valid number -7
line 6: invalid, please try again
fscanf matched 1 value(s): a=42, b=0 (unchanged)
next unread character: 'a'
read_intreads a full line, then letsstrtolconvert it. Theendpointer shows where conversion stopped.- Three checks reject bad input: no digits at all (an empty line or “hello”), extra characters after the number (“12abc”), and values outside the
intrange (“99999999999”), detected througherrno == ERANGEand theINT_MIN/INT_MAXlimits. - Because the whole line was consumed, a bad line never affects the next read. The program can simply ask again.
fscanf(in2, "%d %d", ...)matched only one value. It stopped at “abc”, leftbunchanged, and left “abc” unread in the stream. Ascanfloop that does not handle this keeps failing on the same characters forever.
Input Functions Compared
| Function | Safe length? | Notes |
|---|---|---|
gets(buf) | No | Removed in C11; never use it |
scanf("%s", buf) | No | Unlimited; stops at whitespace |
scanf("%19s", buf) | Yes | Width must be one less than the buffer size |
scanf("%d", &n) | n/a | Check the return value; bad input stays in the buffer |
fgets(buf, size, stdin) | Yes | Reads a whole line, keeps the newline |
getline(&buf, &cap, stdin) | Yes (grows) | POSIX, not standard C; allocates as needed |
Common Mistakes
- Ignoring the return value of
fgetsorscanf. - Forgetting the newline that
fgetskeeps, so comparisons such asstrcmp(ans, "yes")fail. - Using
atoifor user input. It returns 0 for invalid text, so you cannot tell “0” from “abc”. - Mixing
scanf("%d")withfgets, wherefgetsthen reads the leftover newline as an empty line.
Practice Exercises
Exercise 1. Using read_int, keep asking until the user enters an age between 1 and 120.
Show answer
int age;
for (;;) {
printf("Age: ");
fflush(stdout);
if (!read_int(stdin, &age)) {
if (feof(stdin)) return 1; /* input ended */
puts("Please type a whole number.");
} else if (age < 1 || age > 120) {
puts("Age must be between 1 and 120.");
} else {
break;
}
}
Exercise 2. Read a yes/no answer with fgets, accepting “y”, “Y”, “yes” or “YES”.
Show answer
#include <ctype.h>
char ans[8];
int yes = 0;
if (fgets(ans, sizeof ans, stdin) != NULL) {
ans[strcspn(ans, "\n")] = '\0';
for (char *p = ans; *p; p++) *p = (char)tolower((unsigned char)*p);
yes = strcmp(ans, "y") == 0 || strcmp(ans, "yes") == 0;
}
Frequently Asked Questions
Should I use fflush(stdin) to clear input?
No. fflush is defined only for output streams; calling it on stdin is undefined behaviour in standard C. Read and discard characters up to the newline instead.
Why does my prompt not appear before input is read?
Output may be buffered. A prompt without \n can stay in the buffer, so call fflush(stdout) after printing it.
Summary
- Read whole lines with
fgets(buf, sizeof buf, stdin)and check forNULL. - Strip the newline with
strcspn; discard the rest of over-long lines. - Convert with
strtoland check for no digits, extra text and range errors. - Never use
getsor unlimited%s.
