按下按键后立即退出包含时间延迟的循环 [英] Exit from a loop that contains time delay immediately after a key is pressed

查看:178
本文介绍了按下按键后立即退出包含时间延迟的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个函数,如果按下某个键或时间用完,该函数将退出倒数计时器循环.我使用时间延迟使倒数计时器开始运行,经过时间延迟后,控制台将刷新.但是,当我按一个键时,它不会从循环中退出.有人可以帮忙吗?

I would like to implement a function that will exit a countdown timer loop if a key is pressed or if the time runs out. I am using time delay to make the count down timer and after the time delay, the console will refresh. however, it doesn't exit from the loop when I press a key. can anyone help?

这是我的代码:

int b=0;

while(minutes_left>0)
{
    for(minutes_left=minutes_left;minutes_left>0 && b==0;minutes_left-=10)
    {
        system("cls");
        banner();
        printf("    TIME LEFT\n");
        printf("----------------\n");
        printf("     %d:%d0\n",(minutes_left/60), (minutes_left%60)/10);
        printf("----------------\n");
        printf("\nPress any key to enter you transaction code and finish parking\n");
        b=kbhit();
        Sleep(10000);
    }

}

推荐答案

kbhit()不等待任何输入,仅在按下某个键时才返回 您进行测试的那一刻.因此,在这种情况下,您永远不会在需要时完全按下按键,而立即进入睡眠模式.

kbhit() doesn't wait for any input, it just returns if there is a key pressed at the very instant you make the test. So in this case you never hit the key exactly when you need to and you're dropping into the Sleep right away.

正常用法类似于:

while (!kbhit())

因此,您可以坐下来等待按键.在您的情况下,由于您想睡觉,您可能应该执行某种倒数"操作来检查按键是否...我的头上没有一个很好的例子,所以我们只想说:

So you can sit and wait for a key press. In your case since you want to sleep, you should probably do some sort of "count down" operation checking for a key press... I don't have a great example off the top of my head so let's just say:

int countdown;
for(minutes_left=minutes_left;minutes_left>0 && b==0;minutes_left-=10)
{
    countdown = 0;
    system("cls");
    ...
    while(countdown++ <= 1000){  // give a second to hit something
        if(b=kbhit())            // if the user presses a key
            break;               // leave the loop early
        Sleep(1);                // else, sleep for 1 ms and try again
    }
    if (b == 0)          // if nothing was pressed
        Sleep(9000);     // sleep for another 9s


我认为您的问题可能是代码中的其他问题……我用旧的Windows计算机除尘并尝试一下:


I think your problem might be else where in the code... I dusted off the old windows computer and gave it a try:

int main()
{
    int i, b = 0, countdown;
    for(i = 0; i<10000 && b ==0; i++)
    {
         countdown = 0;
         system("cls");
         printf("menu stuff %d\n", i);
         while(countdown++ <= 1000) {
           if(b = kbhit())
              break;
           Sleep(1);
         }
         if(b == 0)
           Sleep(9000);
    }
    return 0;
}

该程序对我有用,以获取输入并突破睡眠机制.

This program works for me to get the input and break out of the sleep mechanism.

这篇关于按下按键后立即退出包含时间延迟的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆