Read user input until ESC is pressed in C

前端 未结 1 1628
清酒与你
清酒与你 2020-12-21 17:46

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

相关标签:
1条回答
  • 2020-12-21 18:25

    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!

    0 讨论(0)
提交回复
热议问题