Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ loop until keystroke

If I want to loop until a keystroke there is a quite nice Windows solution:

while(!kbhit()){ 
    //...
}

But this is neither an ISO-Function nor works on other Operating Systems except MS Win. I found other cross-plattform solutions but they are quite confusing and bloated - isn't there another easy way to manage this?

like image 652
NaN Avatar asked Aug 18 '11 10:08

NaN


2 Answers

No, C++ standard doesn't define concepts like 'keyboard' and 'keystrokes', because not all systems have such things. Use a portable library, maybe ncurses should have something.

like image 59
Yakov Galka Avatar answered Oct 14 '22 10:10

Yakov Galka


You can use the next version of kbhit() for *nix OSes:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}
like image 43
sergzach Avatar answered Oct 14 '22 09:10

sergzach