2012-11-24 116 views
-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); 
} 
+1

什麼是「C-Free 5.0」?如果這是一個模糊的C編譯器,你可能更好地切換到gcc(如果你在Window上,則爲mingw)。 – ThiefMaster

+0

http://stackoverflow.com/q/6731317/1273830可能的重複哦等你已經看到了這個問題?的kbhit? O_O – Prasanth

回答

1

您在最裏面的while循環中「忙於等待」。這可能不是最好的解決方案,但如果這是你想要做的,你需要在該循環中添加一個測試來檢查一個密鑰是否被擊中。

+0

太棒了...!我懂了...非常感謝。 –

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