What is the best way to clean the keyboard buffer [closed]

0

I have seen in several forums that you should use setbuf (stdin (NULL), or getchar I am new to C and I am in doubt on this subject

    
asked by anonymous 09.08.2018 / 20:19

2 answers

1

The problems with the keyboard buffer are generally given by the scanf () function (as far as I know so far).

A brief description of this "problem":

This problem only occurs (I might be wrong) when we want the program to read a character or char array, since we will always have to enter ('\ n') to 'close' the scanf function and this enter will be in the input buffer, but what happens when the enter is in the input buffer (stdin)? We must remember that the function scanf will always read what is stored in stdin, when we enter enter it "closes" the scanf function but it is still there, the next scanf (if there is one) will "catch" this enter and we have the problem, if we test this "error" reading integers will not occur because the enter ('\ n') is not integer.

I'll come up with two ways to solve this problem without adding any extra function in the code.

1 - The buffer problem only occurs from the second implementation forward, so we can add a space before the type indicator, scanf ("% c", & character);

2 - Add an additional parameter in the first scanf () that reads a character just after the "main" parameter, scanf ("% c% * c", & character);

In the first example I used a space (this will be useful later as in the sscanf () function) because it will ignore all white space as spaces, enters, tabs. In the second one I used the * because it will indicate to the program to ignore the data that should be there (enter in the case).

I recommend reading this article: link

To use all (or almost) of the benefits that the scanf () function offers I suggest scanning for scansets.

And my explanation of buffers is not so good, so do some research.

I think it was all;)

I just remember that in the sites where I read about buffer problems they recommend avoiding the use of fflush () to clean the input buffer (stdin), because in this case the fflush () function has undefined behavior (according to the faces that maintains the language).

    
12.08.2018 / 22:49
0

Look, one way that my teacher used to clean the keyboard buffer for all types of reading was fflush (stdin) and I really recommend it, because I used it a lot, and avoided many bug when I was reading from the keyboard.

    
11.08.2018 / 22:19