On Windows, I have the following code to look for input without interrupting the loop:
#include <conio.h>
#include <Windows.h>
#include <iostream>
int main()
{
while (true)
{
if (_kbhit())
{
if (_getch() == 'g')
{
std::cout << "You pressed G" << std::endl;
}
}
Sleep(500);
std::cout << "Running" << std::endl;
}
}
However, seeing that there is no conio.h
, whats the simplest way of achieving this very same thing on Linux?
The closest you can come is some sort of third party library that handles the portability issues for you. Curses probably comes the closest to doing that. Otherwise you have to write your own clear(), kbhit(), and getch() functions, with separate versions of each for each operating system.
kbhit function is used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio. h”. If a key has been pressed then it returns a non zero value otherwise returns zero.
The kbhit is basically the Keyboard Hit. This function is present at conio. h header file. So for using this, we have to include this header file into our code. The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero.
If your linux has no conio.h
that supports kbhit()
you can look here for Morgan Mattews's code to provide kbhit()
functionality in a way compatible with any POSIX compliant system.
As the trick desactivate buffering at termios level, it should also solve the getchar()
issue as demonstrated here.
The ncurses howto cited above can be helpful. Here is an example illustrating how ncurses could be used like the conio example:
#include <ncurses.h>
int
main()
{
initscr();
cbreak();
noecho();
scrollok(stdscr, TRUE);
nodelay(stdscr, TRUE);
while (true) {
if (getch() == 'g') {
printw("You pressed G\n");
}
napms(500);
printw("Running\n");
}
}
Note that with ncurses, the iostream
header is not used. That is because mixing stdio with ncurses can have unexpected results.
ncurses, by the way, defines TRUE
and FALSE
. A correctly configured ncurses will use the same data-type for ncurses' bool
as the C++ compiler used for configuring ncurses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With