简体   繁体   中英

Clearing keyboard buffer in C++

I one part of my application I have used Sleep(5000) (I need to wait 5 sec)

The problem is that if the user presses any keyboard key during these 5 seconds, the keys will be read after sleep and it causes problems for my app.

How can I empty the buffer after sleep?

I tried cin.clear() and setbuf(stdin, NULL) but they can't clear the buffer if there is more than one character in the buffer.

The two functions you are using don't have the effect you expect them to have:

  1. clear() doesn't affect the buffer at all but rather clears the error flags. That is, if there was an unsuccessful read a flag is set ( std::ios_base::failbit ). While any error flag is set (there are a few more), the stream won't attempt to read anything.
  2. setbuf(0, 0) affects the stream's internal buffer to not exist (calls with non-null values have implementation-defined meaning which is typically "do nothing"). This is generally a Bad Idea because it causes the streams to be very slow. Also, the keys pressed by a user are probably not stored in this buffer anyway but rather in the operating systems input buffer until they are sent to application (there are platform specific ways to turn off the operating system input buffer, eg, on POSIX you'd use tcsetattr() to set the input into non-canonical mode).

In either case, not having a buffer doesn't really help you anyway: The user may very well have typed valid input. The proper approach is to attempt reading the available input and, if this fails, to rid of the offending character (or characters). To this end you'd attempt to read the input and if it fails you'd clear() the stream and ignore() one or more characters (this example ignores an entire line; call ignore() without parameters to just ignore one character):

T value;
while (!(std::cin >> value)) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

You always need to verify that the input was successful anyway and the few extra lines are just adding a bit of recovery code.

The simplest way to clear the keyboard input buffer is

while(kbhit()) getch();

just put that code in your program wherever you want to clear your buffer .

headerfile needed for that is conio.h

This seems to work for Windows 10 compiled with Code::Blocks:

#include <conio.h>
/**
 * clears keyboard buffer
 *
 * @author Shaun B
 * @version 0.0.2
 * @fixed 15-01-2016
 */
void clearKeyboardBuffer()
{
    while (_kbhit())
    {
        _getche();
    }
}

Then called from where is needed in your C++ script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM