John Howard said:
I'm trying to write a simple press any key routine, but am having some
problems. Here is the routine:
void PressAnyKey ()
{
cout << "Press Any Key";
do{}while (!kbhit());
getch();
cout << endl;
}
When it runs, the next part of the code is to read using a similar kbhit(),
getch() routine, but it reads in whatever was pressed during the press a
key. If I add an extra getch(), then it just sits there until you press it
twice.
Any ideas?
John
I'm not sure if I'm getting your question right, but it seems like the
program is running so fast that the next "press any key" loop is called
while the user is still holding down the button? You could just add in a
delay, something like
for (unsigned long x = 100000; x!=0; x--);
I doubt that's long enough, but just keep increasing the number. Of course,
this is a bad way to do it, as CPU speeds change, and thus that loop will
not be the same length of delay on every computer. I, unfortunately, cannot
see another standard way of doing this.
Most compilers, however, have an extention, the system() function, which is
nonstandard, but can do exactly what you want. It literally tells the OS to
do something, so by its very nature it is very OS dependent. Do this only if
you are going to use this on a single OS. For example, in Win32 (and perhaps
even Win16, but nobody cares about that anymore) you could do:
system("pause");
In Win32, system() is the equivalent of going start->run and typing in
whatever's inside those quotes. Pause is a recognized DOS statement which
displays "Press any key to continue..." and waits for a keypress. That
should do better if you're willing to do something nonstandard.
Another non-standard option but commonly found extention is also available
for your compiler. Check for something like wait() or something like that.
This function will usually allow you to pause for an integral number of
seconds. This is, obviously, a better way of doing it than the delay loop,
as it will remain the same speed on every computer.
Hope that helped