This question already has an answer here:
- getch and arrow codes 11 answers
I want to take input from the user and check if the user gave up arrow key as the input. I have tried getch function but it only allows user to input a character. I want that user may input up/down arrow key or any string containing more than one characters. Later I wish to check if the user gave up/down key as input or some other string.Please help.
If you must insist on not looking here to find your answer...
Why do you need to use
getch()
? You could just as easily use any other function to get the input and do the work for you.In my example I have used
fgets()
if you so desire.When an up-arrow is entered at the terminal, it might look different on each computer. For example, on my computer when I enter an up arrow it looks like this:
^[[A
. However it looks though,fgets()
does take up-arrows as input. As you saw in the linked question:'A' for an up-arrow, 'B' for a down-arrow, 'C' if you enter a right-arrow, and 'D' if you enter a left-arrow. In my example I have only handled up-arrows, but it should be easy to adapt the program to detect other arrows as well.
Now on to the example:
We detect an up arrow by checking if there is a
'\033'
(note that with octal codes like this, you do not need the 0 so checking for'\33'
is also valid), and if there is, then we check two characters ahead (to skip the'['
) withif(input[i+2] == 'A')
. If this is true, we know an up arrow key will have been entered.Let's run some example tests (remember that in my terminal, an up arrow key looks like
^[[A
):So, in conclusion, I don't know why you thought that the possible duplicate did not work since you couldn't use the
getch()
. The function that you use to get the input is completely irrelevant. The only important part in this process is understanding how arrow keys are entered in the terminal.