2

我想实现一个函数,如果按下一个键或时间用完,它将退出倒数计时器循环。我正在使用时间延迟来制作倒数计时器,并且在时间延迟之后,控制台将刷新。但是,当我按下一个键时,它不会退出循环。谁能帮忙?

这是我的代码:

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);
    }

}
4

2 回答 2

6

kbhit()不等待任何输入,如果在您进行测试的那一刻有按键按下,它只会返回。因此,在这种情况下,您永远不会在需要时准确地按下键,并且您会立即进入睡眠状态。

正常用法是这样的:

while (!kbhit())

所以你可以坐下来等待按键。在你的情况下,因为你想睡觉,你可能应该对按键进行某种“倒计时”操作检查......我没有一个很好的例子,所以让我们说:

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 计算机并试一试:

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;
}

该程序适用于我获取输入并摆脱睡眠机制。

于 2012-12-19T13:25:27.390 回答
2

做额外的循环等待更小的时间粒度:

int b=0;
int count;

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");

        // replacing your's
        //b=kbhit();
        //Sleep(10000);

        // with inner loop
        for(count=0; count<100&& (b=kbhit())==0; count++) {
            Sleep(100);
        }

        // this loop will wait for 10000 milliseconds but in portions of 100
        // periodically it will check keyboard
        // user will be required to keep key pressed for at least 0.1 second
        // to be caught by the loop

    }

}

顺便说一句,你有什么for附加的内部while

于 2012-12-19T13:46:40.780 回答