Search code examples
carrow-keys

What values do arrow keys return with getch()?


I read that you have to use getch() twice to get a value when an arrow key is pressed. The first call returns 0 for arrow keys and the second call returns another value (eg. 77 for right arrow keys). I wrote the following program to confirm this, but the first value I get is 224, not zero:

#include <stdio.h>  
    int main()  
    {  
        printf("Start: (x to quit)\n");  
        int d = getch();  
        int e = getch();  
        printf("%d", d);  
        printf("\n%d", e);  
    }  

Why is the first value not zero, and what is the significance of 224?


Solution

  • The "escape" code 0 applies to the numeric keypad (with NumLock off). The dedicated cursor control keys (and Home etc) use the escape code 224. Please try this:

    #include <stdio.h>
    #include <conio.h>
    
    int main()
    {
        int d=-1, e=-1;
        printf("Start:\n");  
        d = _getch();  
        if (d == 0 || d == 224)
           e = _getch();  
        printf("%d %d\n", d, e);
        return 0;
    }
    

    Note too that the MSVC function getch() is deprecated, use _getch() (these are non-echoing versions of getche() and _getche()).