简体   繁体   English

如果按下任何键,则中断c ++

[英]Break if any key is pressed c++

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. 如果用户在Sleep(毫秒)内按下任何键,我想退出while循环,就像在毫秒内按下任何键时停止一样。 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 平台:Windows

There is no C++ language solution to do this. 没有C ++语言解决方案可以做到这一点。

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). 调用该函数,而不是调用Sleep (这也不是C ++函数)。 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). 从该函数返回时,请检查返回代码以查看是否由于存在可用输入(用户按下一个键)或超时(用户未按下一个键)而返回了。

You can use kbhit() . 您可以使用kbhit() Try this: 尝试这个:

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

This'll work if you're working with windows. 如果您使用的是Windows,它将可以正常工作。 If you are with linux you can also copy paste kbhit.hy kbhit.cpp from http://linux-sxs.org/programming/kbhit.html and add it to your project. 如果您使用的是Linux,则还可以从http://linux-sxs.org/programming/kbhit.html复制粘贴kbhit.hy kbhit.cpp并将其添加到您的项目中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM