【问题标题】:exit a loop by taking esc as input from user [duplicate]通过将 esc 作为用户的输入退出循环[重复]
【发布时间】:2016-03-22 16:12:19
【问题描述】:

假设我处于无限循环中,我希望用户以整数形式输入数据。然后数据将被传递给另一个函数以用于其他目的,这个过程将继续进行,直到用户输入 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 值作为数据输入,它会退出我不想发生的循环?

【问题讨论】:

    标签: loops while-loop infinite-loop exit-code


    【解决方案1】:

    正如 dingrite 在他的另一个回答中所写:

    最好的办法是创建一个自定义的“GetAsyncKeyState”函数,该函数将使用 #IFDEF for windows 和 linux 来选择适当的 GetAsyncKeyState() 或等效函数。

    没有其他方法可以达到预期的效果,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;
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 2018-07-25
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多