1

I tried to make a simple program to detect the arrows (up, down, right, and left) like shown in my code:

#include <iostream>
#include <conio.h>
#define up 72
#define down 80
#define right 77
#define left 75

using namespace std;
 

int main(){
    int n = 0;

    for (int i = 0 ; i < 4 ; ++i){
        n = getch();
        if (n == 72) cout << "UP\n";
        else if (n == 80) cout << "DOWN\n";
        else if (n == 77) cout << "RIGHT\n";
        else if (n == 75) cout << "LEFT\n"; 
        else cout << "NO\n";    
    }

            
return 0;
}

So it is supposed that the loop will iterate 4 times but it actually iterates 2 times and this what is given to me when I press the up key 2 times :

The Output

So what should I do and thanks in advance

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • 1
    The output looks like it accepted 4 characters. Are you pressing any other keys in between the up key? – cigien Sep 11 '20 at 20:28
  • 3
    Can you modify the last output instruction to output `n`? `else cout << "NO " << n << "\n";` What happens if you do that? – damix911 Sep 11 '20 at 20:32
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Pranav Hosangadi Sep 11 '20 at 20:35
  • 1
    Also, have a look at this: https://stackoverflow.com/questions/51792349/getch-returns-2-characters-when-i-type-one It may be a Windows bug I guess. Does it also happen with non-arrow keys? For instance what happens if you press a letter key? – damix911 Sep 11 '20 at 20:35
  • 1
    @damix911 it's quite possible that the arrow keys generate a two character sequence, even if there's no Windows bug. – Mark Ransom Sep 11 '20 at 20:40
  • 4
    It is clearly stated in Microsoft's documentation for [`_getch`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=vs-2019) that arrow keys and function keys return two codes. These should be a `0xE0` (indicating an extended character) value followed by the key scan code. – 1201ProgramAlarm Sep 11 '20 at 20:51
  • @1201ProgramAlarm and just for completeness it should be noted that 0xE0 will be either 224 or -32 in decimal. – Mark Ransom Sep 11 '20 at 21:08
  • @Mark Ransom, 1201ProgramAlarm. Thank you, I kinda remembered something about the arrow being an extend character from my old console programming days, but when I looked it up in Google it suggested that it could be a bug. But to me it totally make sense that there is something different about the arrow keys. That is why I asked [what happens when the user presses a letter](https://stackoverflow.com/questions/63853878/arrows-detection-in-c#comment112915325_63853878). – damix911 Sep 11 '20 at 23:31
  • It looks like the OP of [this other question](https://stackoverflow.com/questions/51792349/getch-returns-2-characters-when-i-type-one) was having a similar problem even with no arrows involved. – damix911 Sep 11 '20 at 23:32

0 Answers0