Debian Linux C++ 如何使击键刹车无限循环

debian linux c++ how to make key stroke brake infinit loop

本文关键字:刹车 无限循环 何使击 Linux C++ Debian      更新时间:2023-10-16

我希望在按键盘上的"q"键时中断一个无穷循环。我没有意识到的问题:标准 getchar 等待用户进行输入并按回车键,这将停止循环的执行。

我解决了"输入"问题,但循环仍然停止并等待输入。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <termios.h>
int getch(void); // Declare of new function
int main (void) { char x;
do 
{ 
   if (x = getch())
      printf ("Got It! n!); 
   else 
   { 
      delay(2000);
      printf ("Not yetn!); 
   }
}while x != 'q');
return 0;
}

int getch(void)
{
int ch;
struct termios oldt;
struct termios newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}

您可以从设备读取它们:

#define INPUT_QUEUE "/dev/input/event0"
#define EVENT_LEN 16
void readEventLine(FILE * in, char * data) {    //read input key stream
  int i;
  for(i = 0; i <= 15; i++) {    //each key press will trigger 16 characters of data,    describing the event
    data[i] = (char) fgetc(in);
  }
}
int readKeyPress() {
  FILE * input;
  char data[EVENT_LEN];
  input = fopen(INPUT_QUEUE, "r+");
  readEventLine(input, data);
}

只是称呼这样的东西而不是你的getch。

改编自 http://www.cplusplus.com/forum/unices/8206/

我必须执行以下操作才能使其正常工作,感谢您的输入!!

#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 
#include <unistd.h> 
#include <termios.h> 
#include <fcntl.h>
int getch(void); // Declare of new function 
int main (void) 
{ 
char x; 
do  
{  
x = getch();
        if (x != EOF)
        {
            printf ("r%sn", "Got something:");
            printf ("it's %c!",x); //  %c - for character %d - for ascii number   
}else  
   {  
      delay(2000); 
      printf ("Not yetn!);  
   } 
}while x != 'q'); 
return 0; 
} 

int getch(void)
{
    int ch;
    struct termios oldt;
    struct termios newt;
    long oldf;
    long newf;
    tcgetattr(STDIN_FILENO, &oldt);             /* Store old settings */
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);           /* Make one change to old settings in new settings */
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);    /* Apply the changes immediatly */
    oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
    newf = oldf | O_NONBLOCK;
    fcntl(STDIN_FILENO, F_SETFL, newf);
    ch = getchar();
    fcntl(STDIN_FILENO, F_SETFL, oldf);
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);    /* Reapply the old settings */
    return ch;
}