我试图通过按任意键随时退出循环。我已尝试过以下代码,但无法完成。需要你的帮助。先感谢您。我使用的是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);
}
答案 0 :(得分:1)
你在最里面的while循环中“忙着等待”。这可能不是最好的解决方案,但如果这是你想要做的,你需要在该循环中添加一个测试来检查一个键是否被击中。
答案 1 :(得分: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";}
}