So for the up key on the keyboard, I get 27, surprisingly for the down key I also get 27. I need my program to behave differently on the up and down key, and I can't seem to figure it out. I am using Linux, and need it to work for 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");
}
}
A getchar() reads a single character from standard input, while a getc() reads a single character from any input stream. It does not have any parameters. However, it returns the read characters as an unsigned char in an int, and if there is an error on a file, it returns the EOF at the end of the file.
Flat out: Arrow keys do not have ASCII codes, because ASCII is a character encoding, not a keyboard encoding.
How do you input arrows in Python? K_UP , K_DOWN , K_LEFT , and K_RIGHT correspond to the arrow keys on the keyboard.
The 27
implies that you're getting ANSI escape sequences for the arrows. They're going to be three-character sequences: 27, 91, and then 65, 66, 67, 68 (IIRC) for up, down, right, left. If you get a 27
from a call to getchar()
, then call it twice more to get the 91
and the number that determines what arrow key was pressed.
As someone else mentioned, this is platform-specific, but you may not care.
Here is the program , which is written to use ncurses library , and display the arrow keys pressed.
#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;
}
while compiling , you have to link to the ncurses library.
gcc main.c -lncurses
Here is a tutorial to help you get started with ncurses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With