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?
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.