Facing problem in detecting keyboard events in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Facing problem in detecting keyboard events in c++

char ch[30]; while(1){ if((GetAsyncKeyState(VK_UP)<0)){ cout<<"up"; }else if((GetAsyncKeyState(VK_DOWN)<0)){ cout<<"down"; }else{ cin.getline(ch,30); } } this is my code and what I am trying to do is I am checking for the event when the user presses "up" or "down" arrow key but in case they don't then the program simply just takes input a string ch. when I am running the program it is only taking input but not detecting the key event but when I remove the else part it detects the up and down key on pressing. Can anyone help me how can I implement both key detection and taking string input?

20th Jan 2019, 2:05 PM
S O U ✌️ I K
S O U ✌️ I K - avatar
4 Answers
+ 3
Consider this code: while(1) { if(kbhit()) { ch = _getch(); if(int(ch)==-32||int(ch)==0) { switch(_getch()) { case 72: //cout<<"UP"; break; case 80: //cout<<"DOWN"; break; default: //take string } } else //take string } } first time _getch() if return -32 or 0 then this means it is an arrow key. next _getch() checks if it is up or down key. (you can also check for left and right key) You can also search on web about working of this code.
21st Jan 2019, 6:35 AM
Lakshay
Lakshay - avatar
+ 3
computer is so fast that before you can press up or down else condition gets reached, what i think you can do is take an input using getch() by using conio.h (it still works in c++14) then using if else statements check if its up key or down key or any other if it is any other then input a string.
21st Jan 2019, 6:28 AM
Lakshay
Lakshay - avatar
+ 1
Lakshay thank you , your code worked perfectly for me
21st Jan 2019, 11:33 AM
S O U ✌️ I K
S O U ✌️ I K - avatar
0
Lakshay can you please provide me an alternative to kbhit() cuz I want to implement this on ubuntu
25th Jan 2019, 11:29 AM
S O U ✌️ I K
S O U ✌️ I K - avatar