How can one flush input stream in C?

fflush(stdin) is undefined behaviour(a). Instead, make scanf “eat” the newline:

scanf("%s %d %f\n", e.name, &e.age, &e.bs);

Everyone else makes a good point about scanf being a bad choice. Instead, you should use fgets and sscanf:

const unsigned int BUF_SIZE = 1024;
char buf[BUF_SIZE];
fgets(buf, BUF_SIZE, stdin);
sscanf(buf, "%s %d %f", e.name, &e.age, &e.bs);

(a) See, for example, C11 7.21.5.2 The fflush function:

int fflush(FILE *stream) – If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

Leave a Comment