gpt4 book ai didi

c - 休眠 N 秒并等待按键

转载 作者:太空宇宙 更新时间:2023-11-04 08:38:24 24 4
gpt4 key购买 nike

我想用 C 语言编写一个程序,它执行一些功能然后休眠几分钟。在此 sleep 期间,我想做一些事情并在按下某个键时退出。

int main()
{
while(1)
{
/*body*/
sleep(300);
}
/*some lines here*/
return 0;
}

无论如何,我可以在 sleep 期间或在任何时候使用非阻塞键监听器退出循环吗?

最佳答案

只是不要休眠 300 秒,而是 300 x 1 秒并检查按键:

int main()
{
while(1)
{
/*body*/
for ( int i=0; i<300; i++ )
{
if (keypressed())
doSomething();
}
}
/*some lines here*/
return 0;
}

编辑:为什么在您的代码中使用 while (1)?你真的想无休止地运行你的程序吗? (在那种情况下,/*some lines here*/ 没有意义。)

关于c - 休眠 N 秒并等待按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25117476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com