C ++ getchar () have data still waiting to be read

I am implementing a key reader in c / C ++. I am using linux. I know that the unbuffered getchar function will return small data values ​​for keys. For all ASCII keys (az, AZ, 1-9, punctuation, input, tab, and ESC), one value is returned from getchar (). For other keys, such as the arrow keys, the ESC key will be displayed, but then when getchar () is called again, it will get a different value (A, B, C or D).

A = 65

B = 66

UP arrow = 27 91 65

F5 = 27 91 49 53 126

ESC = 27

full table here

Is there a way to check if there are more characters to read, or is there just one character? When the key is read and the first value is ESC, I do not know if this is a function key starting with ESC or if it is just an ESC key.

#include <stdlib.h> #include <stdio.h> #include <sys/ioctl.h> #include <iostream> #include <string> #include <termios.h> #include <unistd.h> using namespace std; int main(int argc, char *argv[]) { int ch[5]; int i; struct termios term; tcgetattr( STDIN_FILENO, &term ); term.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &term ); ch[0] = getchar(); // If ch[0] = 27 and there is more data in the buffer // printf("You pressed a function key"); // Else // printf("You pressed ESC"); return 0; } 
+4
source share
3 answers

You can mark stdio nonblocking when you get the escape, and then read as much as possible. You need to enable <fcntl.h>

 if (ch[0] == 27) { int flags = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); for (;;) { int c = getchar(); if (c == EOF) break; printf("%u ", c); } fcntl(STDIN_FILENO, F_SETFL, flags); puts("\n"); } 

There is still a problem with two keys one after another, as the loop will be read until more data is available.

0
source

After you get the first ESC character, you can read other characters without waiting (for example, setting c1cc [VMIN] = 0 and c_cc [VTIME] = 0 in the termios structure), then if the characters found do not match, you insert the characters, which you read into the buffer to read. Then, next time, you first return buffered characters, if any.

0
source

Add getchar () inside the loop and exit the loop when the key entered is ENTER. For instance:

 char ch[5]; int i=0; while(1) { ch[i] = getchar(); if('\n'==ch[i]) { break; } i++; if(i==5) { break; } } 
-1
source

Source: https://habr.com/ru/post/1482086/


All Articles