【发布时间】: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。