问题
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?
回答1:
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;
}
回答2:
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.
来源:https://stackoverflow.com/questions/7105678/c-loop-until-keystroke