2016-03-22 28 views
-1

讓我說我在一個無限的while循環中,並且我希望用戶以整數形式輸入數據。然後數據將被傳遞到另一個函數用於其他一些目的,這個過程會一直持續下去,直到用戶輸入esc代替數據,並且我希望循環在那一點中斷。我該怎麼做?通過以esc作爲用戶輸入來退出一個循環

while(1) 
{ 
    printf("enter the data that need to entered\npress esc to exit\n"); 

    scanf("%d",&n); 

    function(n); 
} 

我嘗試使用的if-else但如果我把ESC的ASCII值作爲數據輸入退出,我不希望發生的循環?

最好的方法是創建一個自定義「GetAsyncKeyState」功能,將使用#IFDEF用於Windows和Linux選擇合適的GetAsyncKeyState()或同等學歷:

回答

0

由於dingrite在他的其他答案寫。

沒有其他方法可以實現預期的結果,cin方法有其問題 - 例如應用程序必須重點關注。

在這個問題請看:C++: execute a while loop until a key is pressed e.g. Esc?

或者你可以用這個例子中其他網頁上找到

#include <stdio.h> 

int main (void) 
{ 
    int c; 

    while (1) { 
     c = getchar();   // Get one character from the input 
     if (c == 27) { break; } // Exit the loop if we receive ESC 
     putchar(c);    // Put the character to the output 
    } 

    return 0; 
} 

希望這有助於嘗試。

相關問題