2016-03-22 18 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; 
} 

希望这有助于尝试。