It returns a non-zero integer if a key is in the keyboard buffer. It will not wait for a key to be pressed.
khbit() reads from the keyboard buffer.. does that mean it won't read key down events and like getch() will only read key events? :'(?
Seems I can use
Code:
while(kbhit()) getch();
to clear the keyboard buffer.
So I have two options depending on how khbit() responds.
Code:
char key;
while(run_time==1){
while(kbhit())
getch();
key = getche();
switch(key){
case '1':
sound(frequency 1);
while(khbit())
delay(1);
nosound() ;
case '2':
sound(frequency 2);
while(khbit())
delay(1);
nosound() ;
default:
run_time=0;
}
or
Code:
char key;
while(run_time==1){
i++;
key = getche();
switch(key){
case '1':
sound(frequency 1);
delay(250);
nosound() ;
case '2':
sound(frequency 2);
delay(250);
nosound() ;
default:
run_time=0;
}
In VS compiler, the second approach works fine, the first doesn't. In the first approach it starts sound but never stops..
code I ran:
Code:
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool run_time = 1;
int i = 0;
char key;
int main() {
while (run_time == 1) {
while (_kbhit())
_getch();
key = _getch();
switch (key) {
case '1':
cout << "\non" << i;
while (_kbhit()) {
Sleep(1);
}
cout << "\noff";
default:
break;
}
}
system("pause");
}
Why this behavior? It's as if the _kbhit() is true even when the user is not clicking a key..
I tried replacing
Code:
while (_kbhit()) {
Sleep(1);
}
with
Code:
while (_kbhit()) {
Sleep(1);
_getch();
}
But that just made it so that the loop is broken even when the user is holding a key..