Friday, July 31, 2009

How to reset _kbhit() in C++?

I'm making a program in C++ that involves the user striking any key in order for the program to stop what its doing and begin something else.





Specifically, it's a slots game, which is extremley simplistic so far. I have three functions. The first function generates three random numbers and puts them into an array, and then it Cout's the array. It repeats that until a key is hit.





while (1)


{


slot[10] = slotfunction(slot, size);


_sleep(100);


cout%26lt;%26lt;"\r";





if(kbhit()) break;





}





*What the function "slotfunction" does is not relevant to my question.*





So, it will keep executing slotfunction() until a key is pressed, then it moves on to the next block of code. However, the next block of code is exactly the same, except that it calls on the function "slotfunction2". Slotfunction2 is a copy of slotfunction, except that it doesnt change the first value.





So, three random numbers are constantly changed on screen, and when you hit a button, the first one remains the same while the othe

How to reset _kbhit() in C++?
No, like this:





while (1)


{


slot[10] = slotfunction(slot, size);


_sleep(100);


cout%26lt;%26lt;"\r";





if(kbhit()) break;





}





while(kbhit()) getch();








That last line, after the end of the loop, will reset kbhit() so the next block of code will again run until a key is hit.





====================


====================


kbhit() remains true as long as keys have been hit that you haven't processed yet. There's a function in conio.h along with kbhit() called getch() which reads a character of input and returns it. So, after your first infinite while loop, do this:





while(kbhit()) getch();





That'll handle the key (or keys) the user hit, allowing kbhit() to be false again.


No comments:

Post a Comment