-1

When I try print getk function direct with printf. It working fine. But when I store it to variable then always output is same. I am trying to get arrow keys as a input

I am using gcc on code block windows 7.

int getk()
{
    int ch;
    ch = getch();
    if (ch == 0)
    {
        ch = getch();
        return ch;
    }
    return ch;
}

void main()
{
    int a, b;
    a = getk();
    printf("%d %d", a, getk());
}

I expect same output in both cases in printf because getk return type and variable a data type are same then why output is diffrent

  • input is upper arrow key expect same output both side but a= 224 and getk()=72 – Manpreet Sidhu Jul 23 '19 at 09:08
  • 2
    You might like [getch and arrow codes](https://stackoverflow.com/questions/10463201/getch-and-arrow-codes) – pmg Jul 23 '19 at 09:12
  • 1
    [This answer](https://stackoverflow.com/a/10473315/440558) (from the link provided by @pmg) explains exactly what's happening, and why you get the numbers you get. – Some programmer dude Jul 23 '19 at 09:15

2 Answers2

0

In this code snippet

   a= getk();
   printf("%d %d",a,getk());

the function getk is called twice (in the assignemnt statement and in the call of printf). The second time it can read for example stored in the input buffer the new line character after pressing by the user the key Return in the previous call of the function.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

According to this question, arrow keys return 3 bytes, so it is not enough to store the result in a single variable. So you must use an array or analyze the characters to get the arrow key:

#include <stdio.h>

int main()
{
    int j;
    char Input[3];

    printf("Input: \n\r");

    j = 0;
    char Single = getch();
    while(Single)
    {
        Input[j++] = Single;
        Single = getch();

        if(j > 2)
        {
            j = 0;
        }
    }

    for(int i = 0; i < 3; i++)
    {
        printf("%d", Input[i]);
    }

    return 0;
}
Kampi
  • 1,798
  • 18
  • 26