2012-08-17 24 views
0

當我按鍵盤上的「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; 
} 
+0

您確定已編譯此代碼嗎?有語法錯誤。爲什麼在'if'中賦值變量? – Leri 2012-08-17 12:03:56

+0

爲什麼標記爲'C++'?看起來像普通的老C對我來說。 – tdammers 2012-08-17 12:05:17

回答

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

+0

shouldnt readKeyPress return something ... like in end add do {@@@@@@@@ = data [i];我 - ; } while(i <0); 返回收集; – Christian 2012-08-17 13:58:12

+0

是的,不是保存到'data'變量,它可以返回值。隨意編輯示例。 – 2012-08-17 15:41:28

+0

它適合你嗎? – 2012-08-27 11:25:34