+ 17
Utilising Arrow Keys in C++
I have a question (finally) ! What would be the standard way of controlling console program flow via arrow keys on C++? As far as I have progressed, I have been successful in using getch() to get the program to respond in various ways to arrow keys upon press, but I would like to know better ways which wouldn't need getch(), or an actual counterpart to getch() which works exactly the same way. @Kenyatta has provided an alternative of using getchar(). I'll just leave this here for extra input.
9 Antworten
+ 9
@Mr.Robot I did a lookup on getchar() and it's from <cstdio>, formally known as <stdio.h> in C.
+ 9
Hi. I'm feeling some exception here because...especially for IoT...a "good" answer requires distinction between ANSI escapes, ASCII, scancodes, ports, portability, terminal types and environment. I did work on that but I need to step away for a while and...maybe you'd just rather I cut through it with this:
Which OS "standard"? There really isn't one. Portability's weird; it's all hacks.
If you don't want to use a hack, try these:
Linux/Android/OSX: "ncurses" for normalizing KEY_UP...etc.
Windows: http://pdcurses.sourceforge.net/
If that's not the ticket, I can come back with a link and some careful attention to getting to the point.
+ 7
@rei cool😊
+ 7
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
if you don't want to display the character you press on the screen, use c = getch();.
else use c = getchar();
then simply compare c with those macros.
if(c == KEY_UP)
// Do something
+ 6
This Code Might Help You
char ch;
ch=getch();
if(kbhit()) //check
if a key is pressed
{
if(ch==57). //move upwards
{
if(ch==61) //move left
{
}
if(ch==63) //move right
{
}
if(ch==62) //move downward
{
}
}
I have used ASCII values in 'if'
+ 5
Getch() comes under the conio.h header file. Whereas getchar() comes under which header file?
+ 3
Instead of getch() you could use WinApi (if you are using Windows ofc). And use events provided in this API, here is comment on how to do it:
http://stackoverflow.com/a/24709138
+ 3
<stdio.h>