C++ 循环直到击键

NaN*_*NaN 5 c++ iso loops cross-platform kbhit

如果我想循环直到击键,有一个非常好的 Windows 解决方案:

while(!kbhit()){ 
    //...
}
Run Code Online (Sandbox Code Playgroud)

但这既不是 ISO 功能,也不适用于 MS Win 以外的其他操作系统。我找到了其他跨平台解决方案,但它们非常混乱和臃肿——难道没有另一种简单的方法来管理这个吗?

ser*_*ach 2

您可以将下一版本的 kbhit() 用于 *nix 操作系统:

#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;
}
Run Code Online (Sandbox Code Playgroud)