随时退出循环

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

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

你在最里面的while循环中“忙着等待”。 这可能不是最好的解决方案,但如果这是您想要做的,则需要在该循环中添加测试以检查密钥是否已被命中。

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

 #include  #include  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 etc";} }