user3180902
user3180902

Reputation:

Why the output is different in both cases?

This is the first code

int main()
{
   int ch;
   while(ch)
   {
       ch=getch();
       printf("%d",ch);
       printf("\n");
   }
   return 0;
}

if in the above code I input

up arrow key 
down arrow key 
right arrow key 
left arrow key 

RESPECTIVELY the the outputs are as following

224
72

224
80

224
77

224
75

but if I remove the LOOP from the code ie

int main()
{
   int ch;
   ch=getch();
   printf("%d",ch);
   printf("\n");
   return 0;
}

and input

up arrow key
down arrow key
right arrow key
left arrow key

RESPECTIVELY then the outputs are as follows

224
224
224
224

From where

224

is coming in the first code and after removing the LOOP where the following numbers are gone

72
80
77
75

Upvotes: 0

Views: 143

Answers (2)

Andreas Fester
Andreas Fester

Reputation: 36630

getch() fetches the next character from the console, but some keys like up arrow key etc. produce two successive "characters". Thus, when you remove the loop, you always only read the first character, but not the second one.

Generally, reading and handling special keys such as the cursor keys is very system specific and not defined in the C language - you would usually use an additional library (e.g. ncurses on Unix) to handle these.

As a last resort, you could also check if the first call to getch() returns the value 224 and in that case call it again, something like this:

int key = getch();
if (key == 224) {
    key = 0x100 + getch();   // arrow keys will have values > 256
}

...

switch(key) {
   case 0x142 : printf("Key up"); break;
   ...
}

But note that this is completely unportable and very system dependent. You should at least encapsulate it in a separate function and define some constants for the various keys.

See also

Upvotes: 3

Mostafa 36a2
Mostafa 36a2

Reputation: 177

224 denoted that it's a functional key , so you have to get the next byte then you'll decide if the next byte was 72 then its Up arrow and so on

here is an example

int a,b;
while(a=getch())
{
    if(a==224)
    {
        b=getch();
        switch(b)
        {
             case 72:puts("Up arrow");break;
             case 80:puts("Down arrow");break;
             case 75:puts("Left arrow");break;
             case 77:puts("Right arrow");break;
         }
     }
 }

your second code will output 224 and stop , because no loop in there , try this :

a=getch(),b=getch();
printf("%d %d\n",a,b);

Upvotes: 0

Related Questions