读取用户输入,直到在C中按下ESC

Qui*_*ala 2 c input

有没有办法读取用户输入,直到按下ESC键(或任何其他键)?我见过关于它的论坛,但他们都是为了C++.我需要制作一个适合C的人.谢谢

Ash*_*ngh 5

让我们检查ascii表中的'esc'字符:

$ man ascii | grep -i ESC
033   27    1B    ESC (escape)
$
Run Code Online (Sandbox Code Playgroud)

因此,它的ascii值是:

  • '033' - 八进制值
  • '27' - 整数值
  • '1B' - 十六进制值
  • 'ESC' - 角色价值

样本程序使用"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;
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!