當我按鍵盤上的「q」鍵時,我想要一個infinit循環中斷。 我沒有意識到的問題:標準getchar等待用戶輸入 輸入,然後按回車鍵,這會暫停執行循環。debian linux C++如何使鍵行程剎車無限循環
我解決了「回車」問題,但循環仍然停止並等待輸入。
這裏是我的代碼:
#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'中賦值變量? – Leri 2012-08-17 12:03:56
爲什麼標記爲'C++'?看起來像普通的老C對我來說。 – tdammers 2012-08-17 12:05:17