Read user input until ESC is pressed in C

2020-02-15 01:56发布

Is there a way to read user input until the ESC key(or any other key) is pressed? I've seen forums about it but they've all been for C++. I need to make one that works for C. Thanks

标签: c input
1条回答
叛逆
2楼-- · 2020-02-15 02:11

Let's check 'esc' character in ascii table:

$ man ascii | grep -i ESC
033   27    1B    ESC (escape)
$

Therefore, it's ascii value is:

  • '033' - Octal Value
  • '27' - Integer Value
  • '1B' - Hexadecimal Value
  • 'ESC' - Character Value

A sample program using integer value of '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;
}

Hope that helps!

查看更多
登录 后发表回答