What does getch() in Turbo C return? I am sure they are not ASCII values for keys pressed

StackOverflow https://stackoverflow.com//questions/25045096

  •  21-12-2019
  •  | 
  •  

Question

What does getch() in Turbo C return? I used it for initializing the arrow keys for a program, the values returned by getch() were 77, 80, 72 and 75 which are ASCII values for alphabets, which clearly indicates that they are not ASCII values. If they are not ASCII values, then what are they?

Was it helpful?

Solution

getch() provided in the non-standard conio.h returns an int:

#include <conio.h>

int     getch(void);

from the reference:

A single character from the predefined standard input handle is read and returned. 
The input is not buffered. If there is a character pending from ungetch 
(see section ungetch), it is returned instead. The character is not echoed to the 
screen. This function doesn't check for special characters like Ctrl-C.

If the standard input handle is connected to the console, any pending output in the 
stdout and stderr streams is flushed before reading the input, if these streams are 
connected to the console.

Return Value

    The character.

Portability

    ANSI/ISO C  No
    POSIX       No 

Your problem with arrow keys is that they are not single-byte characters. In order to handle arrow keys you must handle multi-byte codes. The numbers you are getting are simply one of the two bytes of the key codes.

For an example of reading the codes see (How to read arrow keys) Cheat code in C programming (when inputted from the keyboard)

OTHER TIPS

getch () function returns two keycodes for arrow keys (and some other special keys), It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.

For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.

So, you may do something like:

char ch = getch ();
if (ch == 0 || ch == 224)
{
    switch (getch ())
    {
    case 72:
        /* Code for up arrow handling */
        break;

    case 80:
        /* Code for down arrow handling */
        break;

    /* ... etc ... */
    }
}

Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top