-
Strange keyboard??
I´m trying to write a program that can handle different keypresses. I´ve downloaded an ASCII table so I know what value each key has http://www.asciitable.com.
If I understand it right there is two different versions of ASCII tabel, one "usual" (0-127) and one extended (0-255). Im using the getch() function and it works well on "alfabetic"(visible) character but when I retreive a value from leftarrow I get a negative value (-32). Is it possible (apperntly it is) to get a negative value?? But what is more strange is that I get the same value for left/right/up/down arrow (-32).
Simple code
Code:
int main()
{
char ch;
ch = getch();
printf(" %d", ch);
return 0;
}
Shouldn´t each key return a different value???
-
A char is unsigned. So a -32 is really 224. Some keys, namely the arrow keys and function keys, return two values. The first number is an escape code (for F1-F10 it's char(0) and for F11, F12, and the arrow keys it's char(224)) and the second number is the actual key value.
Code:
int main()
{
char ch;
do
{
ch = getch();
printf(" %d", ch);
} while (ch != 27); // loop until press escape
return 0;
}
Try this code. When you press the left arrow key you should get 224 and 75.
-
Whoops. Cast the char into an unsigned integer.
printf(" %d", unsigned int (ch));
-
I just toyed with this same issue not long ago. I never got an absolute confirmation that this would cause random errors, but it traps function and arrow keys.
Code:
unsigned key1, key2;
do
{
key1 = getch();
if(key1 == 0)
{
key2 = getch();
switch(key2)
{
case 72 /*up arrow */
and so on
};
}
else
{
switch(key1)
{
do whatever here.
printf("%c", key1);
};
}
}while(sentinel == true);
-
here...
Code:
#include <stdio.h>
#include <conio.h>
main()
{
char c;
printf("KEY\tCODE\n");
while ((c = getch()) != 27) //as long as 'Esc' is not pressed
{
printf("%3c\t%4d\n", c, (int) c);
}
}