Recieving info in a console application

Hello,

Does somebody know how I can read any pressed keys? for example, when my program is open en you press left, I want my program to say that you pressed the left button. does anybody know how I can figure that out? Thank you!

Jyy.
One solution is to use _getch(). Be careful, though, because keys like the arrow keys are extended, so they actually return two vaues.
1
2
3
4
5
6
7
8
9
10
11
12
#include<conio.h>

int main(){
    char x, y;

    // If you press the left arrow key...

    x=_getch(); // x = 224
    y=_getch(); // y = 75

    return 0;
}
Last edited on
Can you explain a bit more? For now I just want the left button, the right button, the up button, and the down of course. and what do I have to be careful with?

Thank you.

edit: can you make a code that says "you pressed the left button!" when you press the left button? then I understand it a lot more I think.
Last edited on
I'll try to explain in more detail, but understand that this is not the best (or technically accurate) explanation. When a normal, printable character is hit only one 8 bit character is sent. With certain other keys (arrow keys, page up, page down, home, delete, etc.), two 8 bit characters are sent: the first one is 0xE0 and the second one is specific to the key that was pressed. This means that if you hit 'a' you'll only need to call _getch once, but if you hit an arrow key you'll need to call it twice. If you only call it once, you'll get the first part (0xE0), but the second part will still be buffered and waiting for you to call _getch again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
    int x, y;

    // If you press the left arrow key...
    while(1){
        x=_getch();
        if(x==224) // 224 means it was an extended key
        {
            y=_getch();

            if(y==75) // 75 means it was the left arrow
                cout << "You pressed the left button!\n";
        }
    }
    return 0;
}


Edit:

To find the codes for other keys, modify the above code so that it outputs the return value of _getch, and then simply press the keys you're interested in.
Last edited on
Really thank you! I understand now. Do you also have the key numbers for right, up and down? of do you know a site where i can find it all? thanks again ;)
Right, up, and down are 77, 72, and 80 respectively. It still may be worth your time to write a simple program that outputs those values when the key is pressed, if for no other reason than to verify that you are using the function correctly.
Thank you!
Topic archived. No new replies allowed.