Home > Enterprise >  How does this clear the input buffer?
How does this clear the input buffer?

Time:11-13

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');

CodePudding user response:

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.

CodePudding user response:

while (strlen(string) > 0 && string[strlen(string) - 1] != '\n');. So, do fgets while the length of string is larger than 0 (that is, while there are characters waiting in the input stream) AND ALSO while the end of the string does not equal newline. If the end of the input equals newline, stop. I am not sure why this code does not go ahead and eat up the newline while it is at it, but it is safe because all standard reading functions ignore the intial newline. @barmar had a good suggestion though (Because fgets() reads from the input buffer. If there's data in the buffer that hasn't been read, fgets() doesn't need to wait for the user to type anything.) But they differ in whether or not they ignore the trailing newline (generated when you press ENTER). fgets keeps the trailing newline, but gets strips it off.

  • Related