-1

我试图通过按任意键随时退出循环。我已经尝试了下面的代码,但它无法完成。得需要你的帮助。先感谢您。我正在使用 C-Free 5.0。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int b=0, i;
    int seconds;
    printf("\nEnter number of seconds : ");
    scanf("%d", &seconds);
    while (b==0)
    {
        for(i=1;i<=seconds;i++)
        {
            time_t end = time(0) + 1;
            while(time(0) < end)
            ;
            seconds -= 1;
            printf("Number of seconds left : %d\n", seconds);
            b=kbhit();
        }

        if(seconds == 0)
        {
            exit(0);
        }
    }
    printf("Number of remaining seconds left : %d\n", seconds);
}
4

2 回答 2

1

您在最里面的 while 循环中“忙于等待”。这可能不是最好的解决方案,但如果这是您想要做的,您需要在该循环中添加一个测试以检查是否已按下键。

于 2012-11-24T12:01:10.427 回答
0

要退出循环,请使用 C++ 中名为 khbit 的函数。当按下任何键时它变为 1 并再次清空它分配按下的键以使用 getch() 清除缓冲区

#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())  // khbit will become 1 on key entry.
        {
            break;    // will break the loop
        }

                     // Try to use some delay like sleep(100);  // sleeps for 10th of second to avoid stress on CPU
    }

                     // If you want to use khbit again then you must clear it by char dump = getch();

                     // This way you can also take a decision that which key was pressed like 

                     // if(dump == 'A')

                     //{ cout<<"A was pressed e.t.c";}
}
于 2012-11-24T13:56:29.563 回答