Sleep()命令处于活动状态时禁用用户输入?
问题描述:
如果我在Sleep()命令处于活动状态时输入内容,我找不到解决此程序退出的解决方案。Sleep()命令处于活动状态时禁用用户输入?
cout<<"Start"<<endl;
Sleep(5000); //<--- if I input anything while this is active the program quits after the time ends
cout<<"End"<<endl; //this is outputted after Sleep(),but the program quits immediately after it
当Sleep()命令处于活动状态还是应该执行其他操作时,是否可以禁用用户输入?请给我你的意见。
答
由于您使用的是Windows睡眠功能,我建议您使用_kbhit()。 您只需减少休眠时间,以便阅读用户输入。
#include <windows.h>
#include <conio.h>
int main()
{
int wt = 50; // Time to wait every cycle
int tt = 5000; // Total time
for(int i = 0; i < tt; i+= wt)
{
Sleep(wt);
if (_kbhit())
break;
}
}
也许增加'std :: cin.ignore(INT_MAX);'得到任何被缓冲的输入。很难说没有更多的代码。或者因为这看起来像Windows,也许[BlockInput()](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646290(v = vs.85).aspx)。 –
对不起,但这不是一个完整的例子。无论任何输入,显示的代码行为都完全相同。 – MSalters
@ MSalters上面的代码是一个通用的例子。问题是,如果您在循环或程序的一部分中使用此示例...并在Sleep()命令处于活动状态时向控制台输入任何内容,程序将退出。 –