3

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;
}
Piotr Siupa
  • 3,929
  • 2
  • 29
  • 65
piyush-balwani
  • 524
  • 3
  • 15

1 Answers1

1

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();
}
Jaydeep
  • 41
  • 3
  • Sir this program initiates a screen, and and not prints any printf statement on pressing keys and when uparrow is pressed then exits without printing "Up Arrow". – piyush-balwani Aug 10 '15 at 07:37
  • sir I got problem in your code. We should use printw in place of printf to print formatted output. Sir but this code works when we are initializing the screen. It is not working on current console. Thanks – piyush-balwani Aug 10 '15 at 07:47
  • I think ncurses comes presetup in linux devices. ri8? @Jaydeep – Amrith Krishna Aug 10 '15 at 08:36
  • @AmrithKrishna ncurses is preinstalled on our lab OS. I have tested this code on ubuntu and it works fine. Though, for making it work on lab OS, we need to change the printf to printw. – Jaydeep Aug 10 '15 at 09:22
  • @piyush-balwani you just need to convert printf to printw in your shell. Nothing else needs to change, I suppose. – Jaydeep Aug 10 '15 at 09:56
  • sir /*initscr(); raw(); noecho();*/ i.e. if i not want to initscr, then this code is not working. – piyush-balwani Aug 10 '15 at 16:55