C++, monitor for keyboard input - c++

I'm brushing up on my general programing skills and I've come across a snag. I'm writing a program that simulates a colony of bunnys. Once this program starts it is autonomous, however, at any point the user should be able to press the 'k' key to cull the population by half. I can't think of a way to do this without pausing the program to wait for user input. Nor can I think of a way to make it so that the program will respond immediately (the program runs in semi-real time using the sleep command). Is there a way to accomplish this without multi-treading and years more experience?

I think this article comes close to what you want to do w/o involving ncurses.

C++ doesn't know anything about keyboards, so any answer to this depends on your operating system and its libraries.

Take a look # the GetAsyncKeyState Windows API call. You should be able to find a suitable place to shoehorn this into your code to detect the keypress.

I'm not sure if this is standard C++, but you can use a C function that checks whether a key is available:
#include <conio.h>
int wmain()
{
if(_kbhit())
{
char ch = _getch();
}
}
EDIT: as Zan Lynx mentioned, this is not standard C++, or even standard C, which is why there is no header. It will work fine in Visual C++ or DOS C++ compilers.

A library like Qt can help you quite a bit. You would create an "application" object, derived from QCoreApplication. In your override of QCoreAPplication::event(Event*), you would handle the event if it's a QKeyEvent containing Qt::Key_K. This is portable across Windows, Mac and Linux.

Try ncurses it's pretty standard in UNIX enviorments. It has special functions to wait for user input with timeout in case nobody press any key.

Related

Open a new terminal screen in C ++

First of all, I have to say that I do not know English exactly. I am improving my English but I am not at a sufficient level yet. Please excuse me for my misspelling and write your answers in the simplest way.
My problem is that I want to run another program made in C ++ when the "1" key is pressed. The files are in the same directory. Can you tell me how to do it?
If you want to make cross-platform for your application, use system with predefined operating system macros.
For example:
#ifdef __FreeBSD__
system("Terminal application object is here");
#endif
#ifdef _WIN64
system("Terminal application object is here");
#endif
I want to run another program made in C ++
The only standard way to run another program in C++ is the std::system function. As per its documentation, this function will call the host environment's shell (also known as command line interpreter). The shell generally has an ability to execute other programs.
However, although std::system is standard, the shell itself is not, so any interaction with it will be implementation defined regardless. The use of std::system is somewhat problematic in many cases because it can potentially introduce shell injection vulnerability to the program. You should never pass any user input into std::system. Given this problem, and the fact that the shell is implementation defined anyway, it is often a good idea to use system specific API to directly execute a program without allowing arbitrary shell commands. How to do that depends on the host environment where the program will run.
Short description of how to do that in POSIX standard systems: First fork the process (if you want to stop executing current program entirely and replace with the new one, then you can skip fork), then in the child process call execv (or one of its sibling functions).
when the "1" key is pressed
When using standard input, a C++ program cannot react to a key being pressed. The way it works, you type the input and press enter to submit.
There may be non-standard ways to react to input in a way that you describe which will also be specific to the host environment.

My kbhit() is not Working On Mac, Making a PingPong Game

I am trying to build a ping-pong game on my mac using C++14 (g++ in terminal) and I am getting this error:
use of undeclared identifier 'kbhit'
here is the code: https://github.com/DemonJAZ/GamesC
The function is in GameManager, class named Input.
Since there is no sentence with a squiggly mark in the end, I took a liberty to invent a couple of my own.
Why am I getting this error?
There is no kbhit function in the C++ language.
Why am I seeing people using it all over the place? Why does it work for them?
They are using it on Windows. It's a Windows function. You are on Mac OS X.
I like to be able to use this function. What should I do?
There are several options.
Develop on and for Windows,
Find a port (i.e. a re-implementation in a different environment) of this function that works on Unix-based systems. I'm sure someone somewhere wrote one. Start with https://www.google.com/search?q=kbhit+mac and if this doesn't help, try https://www.google.com/search?q=kbhit+linux. In fact https://www.google.com/search?q=kbhit+ncurses will probably return the best results, but it's kinda hard to guess if you don't know exactly what to look for.
When in Rome do as Romans do. Write to the widely used Unix terminal API known as curses (you probably want the ncurses version).

How to make a long beep in c++?

I'm making a program in c++ that reads Morse Code and prints it to the terminal, and gives the user the option to hear it. I know that, in order to make a "beep," you can use:
cout<<'\a';
However, since Morse Code contains with longer and shorter beeps, I would like to know how to make longer beeps than what would be produced by this command.
I'm using a Mac.
If you write multiple bells. i.e. cout << "\a\a\a\a" it will come out as a longer beep.
However you also need a way to write the "silence" between the beeps, and the bell sound may be different from one environment to another, so this is not really a good approach.
There is no standard library support for controlling sound on the computer, but if you look for platform-specific functionality, you are likely to find it, and ultimately this will give much better results.

What should i do if i want to use functions that are not standard and are due to compiler specific API?

I have been using the very very old Turbo C++ 3.0 compiler.
During the usage of this compiler, I have become used to functions like getch(), getche() and most importantly clrscr().
Now I have started using Visual C++ 2010 Express. This is causing a lot of problems, as most of these functions (I found this out now) are non-standard and are not available in Visual C++.
What am I to do now?
Always try to avoid them if possible or try their alternatives :
for getch() --- cin.get()
clrscr -- system("cls") // try avoiding the system commands. check : [System][1]
And for any others you can search for them .
The real question is what you are trying to do, globally.
getch and clrscr have never been portable. If you're trying
to create masks or menus in a console window, you should look
into curses or ncurses: these offer a portable solution for
such things. If it's just paging, you can probably get away
with simple outputing a large number of '\n' (for clrscr),
and std::cin.get() for getch. (But beware that this will only
return once the user has entered a new line, and will only read
one character of the line, leaving the rest in the buffer. It
is definitely not a direct replacement for getch. In fact,
std::getline or std::cin::ignore might be better choices.)
Edit:
Adding some more possiblities:
First, as Joachim Pileborg suggested in his comment, if
portability is an issue, there may be platform specific
functions for much of what you are trying to do. If all you're
concerned about is Windows (and it probably is, since system(
"cls" ) and getch() don't work elsewhere), then his comment
may be a sufficient answer.
Second, for many consoles (including xterm and the a console
window under Windows), the escape sequence "\x1b""2J" should
clear the screen. (Note that you have to enter it as two
separate string literals, since otherwise, it would be
interpreted as two characters, the first with the impossible hex
value of 0x1b2.) Don't forget about possible issues of
redirection and flushing, however.
Finally, if you're doing anything non-trivial, you should look
into curses (or ncurses, they're the same thing, but with
different implementations). It's a bit more effort to put into
action (you need explicit initialization, etc.), but it has
a getch function which does exactly what you want, and it also
has functions for explicitly positionning the curser, etc. which
may also make your code simpler. (The original curses was
developed to support the original vi editor, at UCB. Any
editor like task not being developed in its own window would
benefit enormously from it.)
Well,
People, i have found the one best solution that can be used everywhere.
I simply googled the definitions of clrscr() and gotoxy() and created a header file and added these definitions to it. Thus, i can include this file and do everything that i was doing prior.
But, i have a query too.
windows.h is there in the definition. suppose i compile the file and make a exe file. Then will i be able to run it on a linux machine?
According to me the answer has to be yes. But please tell me if i am wrong and also tell me why i am wrong.

Capturing a keystroke in C++

I have been doing some reading, and I see that I can use getch() to get a keystroke. What I have seen is that this is considered bad practice, however I have seen conflicting opinions. I am writing a console application for my class, and would like to be able to move a marker(*) around the screen based on the arrow keys being pressed. Is getch() the right way to go about this, or is there a better method to capture it. I want them to just be able to push the arrow, not need to push enter or anything. I don't need the code specifically, I just want to know if I should avoid getch(), and if so, what functions are there for this type of idea.
getch() is not a standard function in either C or C++. It's found in some obsolete compilers, such as Turbo C and it's also defined in certain commonly used libraries such as curses, but in any case it's a C function, not C++. For C++ you should probably just stick with standard C++ I/O. If you can't do this for some reason then go for the most portable option, e.g. curses.
You want to read from the terminal in non-canonical mode. Use tcsetattr() to turn off the ICANON flag.
Use getch() if it works. Why not?
On Windows you can use pdcurses: http://pdcurses.sourceforge.net/, that is compatible with ncurses.