-
Keyboard input problem
This code does exactly what I've been looking for, for some time
but, what does this code do. It doesn't ask for input at the
second getch(). Could somebody please take theris time and
explain this code quite detailed? Thanks in advance.
Code:
#include <iostream.h>
#include <conio.h>
int main()
{
int c = getch();
if (c == 0 || c == 224)
{
c = 256 + getch();
if ( c == (256+72))
cout << "UP";
}
}
-
The reason is that the if statement fails, so that is why you never reach the second getch().
The above line gets a character as input from the console. If the ASCII value returned is equal to 0 or 224, then execution enters the if block.
This might be a better example to show you how it works:
Code:
#include <stdio.h>
int main()
{
int c = getchar();
if(c == 'a')
printf("A was pressed\n");
else if(c == 'b')
printf("B was pressed\n");
else
printf("Some other key was pressed\n");
return 0;
}
As you can see in the above code, I used getchar() instead of getch(). The reason is that getchar() is a portable version of getch(). The only difference is that getchar() requires you to press the enter key after entering in a character.
-
Some keys - for example cursor arrow keys like "UP" are transmitted as TWO bytes (hence two calls to getch() )
The clue that byte 2 is coming is based on the two magic values of byte 1 (namely 0 or 224)
-
Pressing these keys places 2 bytes in the input buffer
UP ARROW,PAGE UP,LEFT ARROW,RIGHT ARROW,END,DOWN ARROW,PAGE DOWN,INSERT,DELETE
getch() when called then twice returns 224 in the first time, and another value key-dependant the 2nd time... Try to guess what 72 is...
And.. ahumm
Code:
c = 256 + getch();
if ( c == (256+72))
How nice!
Code:
//Lets see if this works!
int main(){
int x;//let it have a random number!
if(x+256 == x+256){
std::cout << "Hey! you're right! You could this be??\n";
}else{
std::cout << "Get or buy a new compiler :P\n";
}
}
-
Thanks for your replies, I understand this alot better now. All help for a noob like me is
very appreciated.