Preventing ANSI Escape Characters in Keyboard Entering C

I have a C program that prompts the user for their name with a little bit of code that reads from stdin in a while loop (until the enter key is pressed). I'm pretty sure the user can only enter ASCII values ​​from 32 to 126.

The problem is when I press the arrow (cursor) keys or something like PAGE_DOWN or whatever ... I end up with the ANSI escape sequence printed to the terminal ([A, [6 ~, etc.] ).

Here is the code section.

char name[6];
char c;
uint8_t i = 0;
while ((c = getchar()) != '\n') {
    if (c == 127 || c == 8) {   // Checks if backspace or del is pressed
        i--;
        name[i] = ' ';
    } else if (c >= 32 && c <= 126) {   // Only legal key presses please!
        name[i] = c;
        i++;
    } else {

    }

    if ((c >= 32 && c <= 126) || c == 127 || c == 8) {
        printf_P(PSTR("%c"), c);
    }
}
name[5] = '\0';
move_cursor(15, 18);
printf_P(PSTR("%s"), name);

      

I, of course, chose to ignore ASCII values ​​outside the 32 to 126 range, so what is the reason for this? Any ideas? Hooray!

+3


source to share


2 answers


This works as expected. With terminal emulations of the VT100 family, pressing the cursor up key, for example, sends the following sequence to your application:

<ESC>[A

      

Now ESC (0x1b) is what gets deprived since it is out of range. But the other characters are perfectly correct.



So, to remove them as well, your program must recognize the terminal exit codes; a simple rule of thumb is to remove all characters from the escape sequence by the next letter. This will not capture all terminal escape sequences, but for the most common use it will.

Here you can view a list of common terminal control sequences

+5


source


The published code does not contain specific information about the key.

To do this functionality, the code must change the "mode" of communication with the terminal.



The normal "prepare" mode where keystrokes echoes are output to the terminal and keystrokes such as "backspace" are processed by the terminal driver.

To enable the desired features, "mode" must be "raw" and "echo" must be disabled.

0


source







All Articles