_kbhit() Question

I've just heard about _kbhit() and I don't know how to use it the right way. How I should write my code to show something on the screen every time the keyboard is hit?

If I do this
1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>
#include <conio.h>
using namespace std;

int main(){
    while(1==1){
        if(_kbhit()){
            cout << "KEYBOARD HIT" << endl;
        }
    }
}

It will show "KEYBOARD HIT" forever, and I just want it to show one time, and then to be needed to press a key again to show "KEYBOARD HIT".
What can I do?
PS: I'm using CodeBlocks
closed account (48T7M4Gy)
The while(1==1) part of the loop involves a condition 1 == 1 which is always true. You have created an infinite loop.

Maybe scrap conio.h and use getchar() or a similar function including a clear/no tricks condition would be a better strategy. Try some of the tutorials / reference material here.

PS Take comfort that Codeblocks is not the problem.
closed account (48T7M4Gy)
Also
http://www.cplusplus.com/reference/istream/istream/get/?kw=cin.get

(http://www.cprogramming.com/fod/kbhit.html)
Last edited on
The non-standard _kbhit() function doesn't remove any characters from the input buffer it just detects if there is a character in the buffer. If you don't remove the character then _kbhit() continue to detect the character.
So how i remove the character from _kbhit() ?
The _kbhit() function doesn't contain anything to remove. You need to remove the character or characters from the input buffer.
So how I do that?
Use a function that retrieves information from the standard input stream, cin for example.
It also works with _getch()
Thank you
Topic archived. No new replies allowed.