Platform-independent detection of arrow key press in C++ - c++

In a C++ console program, I've found how to detect and arrow key on Windows, and I've found a lot of other stuff that had nothing to do with the question (despite what I thought were good search terms), but I want to know if there is a platform-independent way to detect an arrow key press. A decent second place for this would be how to detect arrow key press in unix and mac. Code fragments would be appreciated.

There's no cross platform way to do it because it's not defined by either C or C++ standards (though there may be libraries which abstract away the differences when compiled on different platforms).
I believe the library you are looking for on POSIX boxes is curses, but I've never used it myself -- I could be wrong.
Keep in mind that it's entirely possible the console program (i.e. gnome-terminal or konsole or xterm) has monopolized the use of those keys for other functions.

As Billy said, there is no standard cross-platform way to do it.
Personally I use this (game-oriented) library for all inputs, cross-platform win/linux/mac : http://sourceforge.net/projects/wgois/

You can do this cross-platform by using SDL2.
Example code:
#include <SDL2/SDL.h>
int main()
{
SDL_Event event;
SDL_PollEvent(&event);
if(event.type == SDL_KEYDOWN)
{
// Move centerpoint of rotation for one of the trees:
switch(event.key.keysym.sym)
{
case SDLK_UP:
// do something
break;
case SDLK_DOWN:
// do something
break;
case SDLK_LEFT:
// do something
break;
case SDLK_RIGHT:
// do something
break;
case SDLK_ESCAPE:
// do something
return 0;
default:
break;
}
}
return 0;
}

Related

Can I get character from keyboard without pausing a program

I'm working on a little project to improve my coding skills and I have a problem. I'm doing a console version of Flappy Bird. So i have a map which is a two-dimensional array of chars and this map have to move to the left. I am moving all elements of an array one place to the left and after that, clearing console and showing moved map. And here is problem, map has to move constantly but player have to control a bird while map is moving. I wanted to use _getch() but it pausing a program. A question is: Can i read a keyboard input without pausing program? I mean that the map will still moving and when i press for example Space in any moment the bird position will change. I'm working on Windows 10
Even if beginners hope it to be a simple operation, inputting a single character from the keyboard is not, because in current Operating Systems, the keyboard is by default line oriented.
And peeking the keyboard (without pausing the program) is even harder. In a Windows console application, you can try to use functions from user32, for example GetAsyncKeyState if you only need to read few possible keys: you will know if the key is currently pressed and whether if was pressed since the last call to GetAsyncKeyState.
But beware: these are rather advanced system calls and I strongly advise you not to go that way if you want to improve your coding skills. IMHO you'd better learn how to code Windows GUI applications first because you will get an event loop, and peeking for events is far more common and can be used in real world applications. While I have never seen a real world console application trying to peek the keyboard. Caveat emptor...
Including conio.h
you can use this method:
#define ARROW_UP 72
#define ARROW_DOWN 80
#define ARROW_LEFT 75
#define ARROW_RIGHT 77
int main(){
int key;
while( true ){
if( _kbhit() ){ // If key is typed
key = _getch(); // Key variable get the ASCII code from _getch()
switch( key ){
case ARROW_UP:
//code her...
break;
case ARROW_DOWN:
//code her...
break;
case ARROW_LEFT:
//code her...
break;
case ARROW_RIGHT:
//code her...
break;
default:
//code her...
break;
}
}
}
return 0;
}
The upper code is an example, you can do this for any key of keyboard. In this sites you can find the ASCII code of keys:
http://www.jimprice.com/jim-asc.shtml#keycodes
https://brebru.com/asciicodes.html
Say me if it has help you!

Function of _kbhit()

I am a beginner at C++ and trying to code a C++ console based snake game. I was stuck when I cannot move the snake without continuously pressing a key. Now I can do by just pressing the key once but I still do not understand the function of _kbhit() which has helped me do it.
void snake_movement(){
if(_kbhit())
switch (getch())
{
case 'w':
y_cordinate--;
break;
case 'a':
x_cordinate--;
break;
case 's':
y_cordinate++;
break;
case 'd':
x_cordinate++;
break;
default:
break;
}
}
The _getch() is a blocking function. If no keypresses are available in the input buffer, it will wait for a keypress to become available in the input buffer. So your program gets stuck inside of _getch() until a key is pressed - and that's why it wouldn't "work" unless you keep the key pressed, so that _getch() can keep returning to your program. It still would get "stuck", because new keystrokes are only available at the key repeat rate. That is: in the best case, _getch() may return a few dozen times per second. But only if a key is pressed down, and if the operating system supports autorepeat for that key.
On the other hand, _kbhit() doesn't block. It returns immediately with a zero value if no keypress is available in the input buffer. Otherwise it returns a non-zero value. That indicates that a key is available, and that you can call _getch() to get it. _kbhit() returning non-zero guarantees that _getch() won't block, i.e. it won't wait but will return immediately with the result you need.

Nested switch gives error and indicates virus (trojan)

Trying to make a program using switch case (nested switch) my system alerted me that my program has a virus (trojan). How is it even possible? I am new to programming (complete novice) so I would be grateful for any help.
The task - to make automated telephonic reply system based upon requirements (just something I wanted to try).
#include<iostream>
using namespace std;
void customer_service()
{
cout<<"Kindly wait for our employees to contact you";
}
void feedback()
{
cout<<"Kindly record your feedback after the beep";
}
void offer()
{
cout<<"You are entitled to accept our one-time offer. You will be directed to one of our employees shortly\n";
}
void satisfied()
{
cout<<"Thanks a lot for calling. Have a great day ahead";
}
int main()
{
int input,yes_no;
cout<<"\nPress 1 if you would want to directly contact our employee\n";
cout<<"\nPress 2 if you wan to give a feedback\n";
cout<<"\nPress 3 if ypu would want to know about our offers\n";
cout<<"\nPress 4 if you are satisfied with our service\n";
cout<<"\nKindly press the required key\n";
cin>>input;
switch (input)
{
case 1:
customer_service();
break;
case 2:
feedback();
break;
case 3:
offer();
cout<<"Would you like to accept our one time offer? You will get a 50% decrease in tariff";
cin>>yes_no;
switch (yes_no)
{
case 1:
cout<<"Congratulations! You have won our one time offer";
break;
default:
cout<<"Guess you didn't like our offer";
break;
}
break;
case 4:
satisfied();
break;
default:
cout<<"Kindly press either one of '1, 2, 3 or 4' keys. Thankyou.";
}
cin.get();
return 0.00;
}
This is the indication of Trojan and the program not executing
It's a false positive.
You may be able to help the situation by initialising your variables. As it is, you do not check that reading into yes_no succeeded, so your program has undefined behaviour. That could make your AV think that you are trying to write a memory exploit.
Otherwise, get better AV!
Some anti virus programs simply have false positives. Just whitelist in this case or get another anti virus.
OR your toolchain itself is infected and you compile bad stuff into your programs (then it's time to clean up your OS)
There is nothing wrong with your code.
Programs like 360 total security are anti-malware products that are designed to run on your mother's machine. They are not appropriate on a programmer's machine. They deal poorly with an executable file that appears from nowhere. Uninstall and consider something less aggressive, Windows Defender for example.
Nested switch cases will work work for sure.
First try like instead of using second switch case use if else condition if still it shows TROJAN thing then its a problem with your compiler.

PDCurses KEY_ENTER does not work

Lets start with what my code looks like then I will explain my problem:
int main {
char ch; //Stores key presses
initscr();
raw();
nonl();
keypad(stdscr, TRUE);
noecho();
//Some code
ch = getch();
switch (ch) {
case KEY_UP:{
//Code that works
break;
}
case KEY_ENTER:{
//Some code- that doesn't work problem being the above
break;
}
//Other case statements
}
Now the problem:
The problem I run into if you haven't already worked it out is that when ever I press the enter/return key on my keyboard absolutely nothing happens.
I have tried changing the KEY_ENTER to '\n' - didn't work - even changed the char ch which when through multiple iterations including int and wchar_t.
All to no avail, and before you say search for answers and send me packing my bags to go onto a perilous adventure through every corner of the interwebs, I have already tried that, if I hadn't I wouldn't have ventured here, in search of aid.
So now my search has brought me here and I ask of you - the lovely people of the interwebs - to help me in my search of the answer I have been looking for
And to who ever may be valiant enough to answer it I give you my up most gratitude and thanks
Try case '\r':. (For good measure, you could do case '\r': case '\n': case KEY_ENTER:, as is basically done in testcurs.c, to capture all possibilities.) The call to nonl() is why you're getting '\r' instead of '\n'.
As for KEY_ENTER, my only excuse is that it's marked "not reliable" in the PDCurses comments. I could pretend that it's meant to represent the keypad's "Enter" key, rather than the key usually marked "Return" in the main part of the keyboard... except that PDCurses also has PADENTER, specifically for that purpose. In truth, like a lot of things in PDCurses, the reason KEY_ENTER is there, and defined the way it is, is a bit of a historical mess.

opencv : Unable to read upper case letters through waitKey

I have a simple switch case as follows inside an infinite while loop, to call functions based on the key pressed by the user. I am programming in C++ using opencv libraries.
The waitKey function used below is able to read the lower case letters i press on the keyboard. I am however unable to read any upper case letters and it still reads and interprets it as the corresponding lower case letter.
Any help in this regard is appreciated. should i be updating my opencv libraries? I installed opencv on ubuntu with the help of this post
os UBUNTU 13.10
opencv version 2.4.8
Pseudo code
while(1)
{`
char k = waitKey(0);
switch(k) {
case 'a' : ... break;
case 'b' : ... break;
case 'A' : ... break; // UNABLE TO READ A here.
}
}
I found a small hint related to your problem on OpenCV forum incase you have not found it yet: http://answers.opencv.org/question/4266/cvwaitkey-upper-lowercase-difference/
I have the same problem (with opencv-4.x).
I think this is due to the fact that I compiled opencv with the cmake option -D WITH_QT=ON (to enable the zoom scroll on images). But Qt interprets q and Q as the same keycode (81); the only thing is that it adds a (shift) modifier.
Let's say you receive a QKeyEvent event in a C++/Qt program. Then you get when pressing:
'Q': event.key() = 81, event.modifiers().testFlag(Qt::KeyboardModifier::ShiftModifier) = true
'q': event.key() = 81, event.modifiers().testFlag(Qt::KeyboardModifier::ShiftModifier) = false
It seems cv::waitKey or cv::waitKeyEx, when opencv uses Qt, does not read the modifiers, just the key code, unfortunately...
So far, the only option I found is to recompile with -D WITH_QT=OFF. Then I can discriminate between Q and q (but also left arrow and Shifted left arrow and so on). But the trade-off is that I can't scroll the images anymore...