C++ getchar() is there data still waiting to be read -


i implementing key reader program in c/c++. using linux. know unbuffered getchar function return little data values of keys. ascii keys (a-z, a-z, 1-9, punctuation, enter, tab, , esc) there single value returned getchar(). other keys, such arrow keys, there esc key read, when getchar() called again, 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 way check if there more characters read or if there single character? when key read , it's first value esc not know if function key starts esc or if 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 , there more data in buffer     // printf("you pressed function key");     // else     // printf("you pressed esc");      return 0;     } 

you can mark stdio nonblocking when escape , read as possible. need include <fcntl.h>

if (ch[0] == 27) {     int flags = fcntl(stdin_fileno, f_getfl, 0);     fcntl(stdin_fileno, f_setfl, flags | o_nonblock);     (;;) {         int c = getchar();         if (c == eof)             break;         printf("%u ", c);     }     fcntl(stdin_fileno, f_setfl, flags);     puts("\n"); } 

there still problem 2 keys after each other loop read until there no more data available.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -