Problem with kbhit()[and getch()] for Linux

Alex Xander picture Alex Xander · Oct 3, 2009 · Viewed 15.2k times · Source
while(ch != 'q') 
{
  printf("looping\n");
  sleep(1);
  if(kbhit()) 
   {
    ch = readch();
    printf("you hit %c\n",ch);
   }
}

This code gives me a blocking getch() like functionality. I am trying to use this code to capture up down arrow keys.

Added: Trying to capture key codes of up arrow gives me 3 chars 27, 91 and 65. Using if/else I am trying pattern matching but I only get 2 chars. Next one is captured when next key is pressed.

I want to capture full words using getchar() while always looking for certain keys all the time(esc, del etc.).

Answer

sambowry picture sambowry · Oct 3, 2009

I can't reproduce Your problem:

#include <unistd.h> 
#include <stdio.h> 
#include <ctype.h> 

#include "kbhit.h" /* http://linux-sxs.org/programming/kbhit.html */

int main(){
  init_keyboard();
  char ch='x';
  while( ch != 'q' ){
    printf("looping\n");
    sleep(1);
    if( kbhit() ){
      printf("you hit");
      do{
        ch = readch();
        printf(" '%c'(%i)", isprint(ch)?ch:'?', (int)ch );
      }while( kbhit() );
      puts("");
    }
  }
  close_keyboard();
}