0

I know how there are different ways of getting keyboard input such as conio.h, but I want to learn how to use this method. the getkey function uses stty for gathering keyboard input.

char getkey()
{
    char c;

    system("/bin/stty raw");
    system("/bin/stty -echo");

    c = getc(stdin);

    system("/bin/stty echo");
    system("/bin/stty cooked");

    return (c);
}

using it, here is how I would detect if the user pressed the a key.

char c;

while (1)
{
    switch (c = getkey())
    {
    case 'a': // stuff
    }
}

the problem is that I don't know how to check for arrow keys. I tried printing the value of c when I press any of the UP/DOWN/LEFT/RIGHT keys, but it shows me multiple numbers. how can I detect them?

  • 1
    It's because they *do* produce multiple numbers... in Windows, for example, if the first response is `0` or `224` you can call `getch()` again for the next detail. – Weather Vane Jun 21 '23 at 18:59
  • @WeatherVane I know that. how would I detect that with my switch case? – KianFakheriAghdam Jun 21 '23 at 19:00
  • 1
    By nesting another switch case? BTW please change `char c;` to `int c;` and `char getkey()` to `int getkey()`. Using `int` also allows you to build a single value from the key pairs. – Weather Vane Jun 21 '23 at 19:01
  • @WeatherVane thanks – KianFakheriAghdam Jun 21 '23 at 19:08
  • @WeatherVane I changed all the `char`s to `int`s, but the value is still multiple – KianFakheriAghdam Jun 21 '23 at 19:18
  • 1
    Yes, it does not change that, but it brings it into line with every other library function that returns a single byte: for example `int getch()` and `int fgetc()`, and it allows you to uniquely encode the arrow and function key values in a single variable. – Weather Vane Jun 21 '23 at 19:20

0 Answers0