0

当我按下键盘上的“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 yet\n!); 
   }

}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;
}
4

2 回答 2

0

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

#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%s\n", "Got something:");
            printf ("it's %c!",x); //  %c - for character %d - for ascii number   
}else  
   {  
      delay(2000); 
      printf ("Not yet\n!);  
   } 

}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;
}
于 2012-09-08T20:21:30.610 回答
0

您可以从设备中读取它们:

#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/

于 2012-08-17T12:11:01.080 回答