Getchar () returns the same value (27) for up and down arrow keys

So, for the up key on the keyboard, I get 27, unexpectedly for the down key I also get 27. I need my program to behave differently with the up and down keys, and I can't figure it out , I use Linux and need it to work on Linux.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { int c = getchar(); if(c==27) { printf("UP"); } if(c==28) { printf("DOWN"); } } 
+4
c keyboard getchar
Mar 09 '13 at 2:26
source share
4 answers

27 means you get ANSI escape sequences for arrows. They will be three-character sequences: 27, 91, and then 65, 66, 67, 68 (IIRC) for up, down, right, left. If you get 27 from a call to getchar() , then call it twice to get 91 , and a number indicating which arrow key was pressed.

As already mentioned, this is platform specific, but it may not matter to you.

+7
Mar 09 '13 at 2:31
source share

Check out the ncurses library at http://www.gnu.org/software/ncurses/ . Linking it to your program will allow you to do all kinds of neat things with key events. Read the documentation and see if you want to use it. It provides exactly the functionality that you say that you are looking for.

Happy coding!

+1
Mar 09 '13 at 2:49
source share

Here is a program that is written to use the ncurses library and displays the pressed arrow keys.

 #include<ncurses.h> int main() { int ch; /* Curses Initialisations */ initscr(); raw(); keypad(stdscr, TRUE); noecho(); printw("Press E to Exit\n"); while((ch = getch()) != 'E') { switch(ch) { case KEY_UP: printw("\nUp Arrow"); break; case KEY_DOWN: printw("\nDown Arrow"); break; case KEY_LEFT: printw("\nLeft Arrow"); break; case KEY_RIGHT: printw("\nRight Arrow"); break; default: printw("\nThe pressed key is %c",ch); } } printw("\n\Exiting Now\n"); endwin(); return 0; } 

when compiling, you must reference the ncurses library.

 gcc main.c -lncurses 

Here is a tutorial to help you get started with ncurses.

+1
Mar 09 '13 at 3:05
source share

You are misleading the keys that you press with the characters that they generate when pressed. Do you expect to get one character when you press the shift key? Try this program:

 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { do { int c = getchar(); printf("c=%d\n", c); } while (1); } 

Try pressing the up arrow and then enter. Then try pressing the down arrow, and then enter. You will see that converting keys to characters is not easy.

0
Mar 09 '13 at 2:31
source share



All Articles