I found this code that clears the input buffer, but I don't really understand how it works. Can anybody explain it in a simple way?
do{
fgets(string,LENGTH,stdin);
} while (strlen(string) > 0 && string[strlen(string) - 1] != '\n');
It's a misnomer to say that it "clears the input buffer". What it does is advance to the next line of input.
The code is a do
/while
loop. It assumes a char array called string
that is at least LENGTH
in size.
The body of the loop reads as much of a line as it can, up to LENGTH - 1
characters:
fgets(string,LENGTH,stdin);
The return value from fgets()
is ignored - this is a bug, because it can mean that string
is not assigned to in a failure case (such as EOF) and we could loop forever.
The condition of the loop checks to see whether we have read up to the end-of-line. There's a test that the string has at least one character (which it will if fgets()
was successful) and then compares the last character to a newline:
while (strlen(string) > 0 && string[strlen(string) - 1] != '\n')
If we see a newline, then fgets()
has read the rest of the line; if not, it read LENGTH-1
characters from a longer input line, and there's still input to consume, so continue looping.
Fixed version:
while (fgets(string, LENGTH, stdin) && string[strlen(string) - 1] != '\n')
;
Simpler alternative:
scanf("%*[^\n]%*c");
Note that in both cases, any stream error will remain, to be detected on the next attempt at input.