Question

I have created an application for detect pressing up and down key on keyboard but nothing will be printed after pressing these keys.

I am using Visual C++ 2010

    #include <iostream>
    #include <conio.h>
    using namespace std;

void main()
    {
        char x;

        while(1)
        {

            x = getch();
            if(x==0 || x==224)
            {
                x=getch();
                if(x==80)
                {
                    cout << "down"<<endl;
                }


                else if(x==72)
                {
                    cout << "up"<<endl;
                }
            }//if x==0 || x=224
        }//while1
    }//main

What can be the problem?

Thanks

No correct solution

OTHER TIPS

Just to answer why it isn't working: You are trying to use your user's input as unsigned. Your character variable is signed so the value is different than you are expecting. An unsigned 224 is a signed -32.

As far as your loop goes I'd suggest changing things to this.

void main()
    {
        char x;

        while(true)
        {
            while(!kbhit()){}
            x = getch();

            if(x==0 || x==-32)
            {
                x=getch();
                if(x==80)
                {
                    cout << "down"<<endl;
                }


                else if(x==72)
                {
                    cout << "up"<<endl;
                }
            }//if x==0 || x=224
        }//while1
    }//main

The program will still loop forever. Then the next loop, which I added, will continue to loop while there are no keys being pressed(buffered). Then getch() grabs the next char from the buffer. Now the problem you were running into, is that you had 224 (0xE0) which is technically correct. However in binary apparently -32 and 224 look the same.

I ran into a bit of the same issue at first, I couldn't figure out why my code wasn't hitting the correct code block and it was because the first character was actually -32 (0xE0)

Hope that is of some help, despite this being a really old question.

You can use the curses.h library. Read their guide and it should be very easy from there. After you take input using getch() (store the input into an int, not a char), you can verify if it's one of the arrow keys using the defined keycodes. Just make sure you used keypad(stdscr, TRUE) before for the program to be able to recognize the arrow keys.

Us kbhit() to get Keyboard Arrow Keys

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top