Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
    }

} 
like image 452
NoNameY0 Avatar asked Mar 09 '13 02:03

NoNameY0


People also ask

How does Getchar work in C?

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.

What is the ascii value of arrow keys?

Flat out: Arrow keys do not have ASCII codes, because ASCII is a character encoding, not a keyboard encoding.

What is up arrow keys called in Python?

How do you input arrows in Python? K_UP , K_DOWN , K_LEFT , and K_RIGHT correspond to the arrow keys on the keyboard.


2 Answers

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.

like image 157
Ernest Friedman-Hill Avatar answered Sep 20 '22 16:09

Ernest Friedman-Hill


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.

like image 27
Barath Ravikumar Avatar answered Sep 21 '22 16:09

Barath Ravikumar