1

I want to break out of a while loop if the User pressed any key during a Sleep(miliseconds), as in stop if any key is pressed during those miliseconds. How do I do that? The loop looks like this:

while (1)
{
    r = rand() % 5501 + 1000;
    Sleep(r);
    cout << "NOW!\n";
    t = clock() / 1000;
    system("pause");
    if (clock() / 1000 < t + 1)
    {
        cnt++;
        cout << "Aaaaand...\n";
    }
    else break;
}

Platform: Windows

Cosmin Petolea
  • 119
  • 1
  • 10

2 Answers2

3

There is no C++ language solution to do this.

You will have to find a platform specific function which waits until there is input available with a timeout. Call that function instead of Sleep (which is also not a C++ function). On return from that function check the return code to see if it returned because there is input available (user pressed a key), or timed out (user didn't press a key).

2

You can use kbhit(). Try this:

bool exit = false;
while(!exit){
    if(kbhit())
         exit = true;
}

This'll work if you're working with windows. If you are with linux you can also copy paste kbhit.h y kbhit.cpp from http://linux-sxs.org/programming/kbhit.html and add it to your project.

blackout
  • 84
  • 9