0

I have a problem with my C++ app and I don't know whether its the code or the terminal. I am trying to detect key presses but when I press a key it just prints it to the screen, i.e. the up arrow prints ^[[A. When i press enter all the code runs at once.

And no, Im not taking user input and then just printing it out.

Any help would be great.

#include <stdio.h>
int main()
{
    char ch;
        do{
            ch=getchar();
             if(ch==65)
                printf("You pressed UP key\n");
             else if(ch==66)
                printf("You pressed DOWN key\n");
             else if(ch==67)
                printf("You pressed RIGHT key\n");
             else if(ch==68)
                printf("You pressed LEFT key\n");
        }while(true);
 return 0;
}
AshMcSpec
  • 23
  • 1
  • 5
  • @Scheff I added a code snippet. I put that in xcode and compiled it with G++, but I think my problem might lie within the terminal. – AshMcSpec Apr 24 '20 at 13:13
  • FYI: [SO: How to detect key arrow key press in C++ in OSX?](https://stackoverflow.com/q/57874850/7478597) where I found a link to [SO: How do I detect arrow keys pressed using curses in C?](https://stackoverflow.com/a/1182680/7478597). You can find more by [google "macos c++ cin arrow keys"](https://www.google.com/search?q=macos+c%2B%2B+cin+arrow+keys). I guess, MacOS isn't that relevant concerning this. If it's a VT100 issue than it's probably similar in Linux and other *ix OSes. – Scheff's Cat Apr 24 '20 at 14:06
  • If you don't get input before pressing ENTER, you have to switch to unbuffered input. FYI: [SO: Capture characters from standard input without waiting for enter to be pressed](https://stackoverflow.com/q/421860/7478597) – Scheff's Cat Apr 24 '20 at 14:11
  • Sorry, your sample code might be perfectly compile in g++ but, actually, it looks like pure C. ;-) (In C++, `#include ` instead of `#include ` and standard lib. things have to be prefixed with `std::` in almost all cases.) – Scheff's Cat Apr 24 '20 at 14:13
  • Thanks for the help – AshMcSpec Apr 24 '20 at 15:14

0 Answers0