Do not use fflush on an input stream
suggest changeIn ISO C, fflush sends buffered output to its destination. Passing an input-only stream such as stdin has undefined behavior. Some implementations define additional behavior, but code that relies on it is not portable.
The removed gets function is also unsafe because it cannot limit how much input is written to the destination array. It was deprecated in C99 and removed in C11. Use fgets instead.
For interactive input, reading a complete line and then parsing it is usually clearer than mixing token-oriented functions such as scanf with line-oriented functions such as fgets:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char line[128];
fputs("Enter an integer: ", stdout);
if (fgets(line, sizeof line, stdin) == NULL) {
fputs("Input error\n", stderr);
return EXIT_FAILURE;
}
if (strchr(line, '\n') == NULL && !feof(stdin)) {
fputs("Line was truncated\n", stderr);
return EXIT_FAILURE;
}
errno = 0;
char *end;
long value = strtol(line, &end, 10);
if (errno != 0 || end == line || (*end != '\n' && *end != '\0')) {
fputs("Invalid integer\n", stderr);
return EXIT_FAILURE;
}
printf("You entered %ld\n", value);
return EXIT_SUCCESS;
}
If a program must continue using scanf, it can explicitly discard the rest of the current line. Always test for end-of-file so the loop cannot run forever:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
/* Discard the remainder of the line. */
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents