Reputation: 544
for using arrow keys, first it has to be stored for analyzing it. That's why I am using scanf
to store it.
But when I try to run this code, and when I press up key, then it is showing ^[[A
and when I press enter then this ^[[A
removes and program exit without printing printf statement of printf("%s",c).
and printf("UP\n").
#include <stdio.h>
int main()
{
char c[50];
scanf("%s",&c);
printf("%s",c);
if (getch() == '\033'){ // if the first value is esc
getch();// skip the [
getch();// skip the [
switch(getch()) { // the real value
case 'A':
printf("UP\n");
break;
case 'B':
printf("DOWN\n");
break;
}
}
return 0;
}
Upvotes: 3
Views: 125
Reputation: 41
You will find it easy if you use the ncurses library. Just go through the documentation to see how to install it. After installing read the part on Interfacing with the key board
Here is a sample code
#include <ncurses.h>
int main()
{
int ch;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
while(1)
{
ch = getch();
switch(ch)
{
case KEY_UP:
printw("\nUp Arrow");
break;
case KEY_DOWN:
printw("\nDown Arrow");
break;
case KEY_LEFT:
printw("\nLeft Arrow");
break;
case KEY_RIGHT:
printw("\nRight Arrow");
break;
}
if(ch == KEY_UP)
break;
}
endwin();
}
Upvotes: 1