【问题标题】:debian linux c++ how to make key stroke brake infinit loopdebian linux c++ 如何使击键打破无限循环
【发布时间】:2012-08-17 12:00:09
【问题描述】:

当我按下键盘上的“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;
}

【问题讨论】:

  • 你确定你已经编译了这段代码吗?存在语法错误。为什么要在if 中分配变量?
  • 为什么这个标签是“C++”?在我看来,这就像普通的旧 C。

标签: c++ linux getchar


【解决方案1】:

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

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

【讨论】:

  • 不应该 readKeyPress 返回一些东西......就像最后添加 do{ collect =+ data[i];一世 - ; }while(i
  • 是的,它可以返回值,而不是保存到data 变量。随意编辑示例。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-04
    • 2013-03-08
    • 2012-04-02
    • 1970-01-01
    • 2018-09-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多