2017-05-06 55 views
0

我想输出每按x秒按下的最后一个按键的ASCII码。每x秒以不同的输出显示东西

作为例子:

如果我按下一个(97),该终端应显示97每x秒。当我现在按w(119)时,程序现在应该打印119而不是97. 到目前为止,我的程序只是打印我按下的第一个键。

以下是主要的,另一个方法:

int main(int argc, char const *argv[]){ 
     printf("Hello World!"); 
     while(1){ 
      movePlayer(); 
      fflush(stdout); 
      sleep(1); 
     } 
     return 0; 
} 

void movePlayer(){ 
    system("/bin/stty raw"); 
    int input = getchar(); //support_readkey(1000); 
    //fprintf(stdout, "\033[2J"); 
    //fprintf(stdout, "\033[1;1H"); 
    printf("\b%d",input); 
    system("/bin/stty cooked"); 
} 

编辑:

随着测试的一点点我现在已经解决了我的问题的方法

int read_the_key(int timeout_ms) { 
    struct timeval tv = { 0L, timeout_ms * 1000L }; 
    fd_set fds; 
    FD_ZERO(&fds); 
    FD_SET(0, &fds); 
    int r = select(1, &fds, NULL, NULL, &tv); 
    if (!r) return 0; 

    return getchar(); 
} 
+0

这是因为'getchar'等待一个字符;你必须使用'read'来代替。 –

回答

0

getchar()等待只有一个字符,所以这个:

while(1){ 
    movePlayer(); // getchar() and printf() here 
    fflush(stdout); 
    sleep(1); 
} 

导致此行为。你读一个字符,你打印它在movePlayer()。然后你刷新输出缓冲区并进入睡眠状态。然后你只需重复,这意味着你必须再次输入。

保存输入并重新打印,如果您愿意。但是,你的功能将会总是等待新的输入到达。


这里是read()所建议的一种尝试,但它也有类似的行为,你的代码,因为它现在是:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

int old_c = -1; 
char c[1] = {0}; 

void movePlayer(); 

int main(int argc, char const *argv[]){ 
     while(1) { 
     movePlayer(); 
     fflush(stdout); 
     sleep(1); 
     } 
     return 0; 
} 

void movePlayer(){ 
    system("/bin/stty raw"); 
    if(read(STDIN_FILENO, c, sizeof(c)) > 0) 
     old_c = (int)c[0]; 
    if(old_c == -1) 
     old_c = (int)c[0]; 
    printf("\b%d", old_c); 
    system("/bin/stty cooked"); 
} 

请仔细阅读read() from stdin去。你可以告诉read()要等待多少个字符然后返回,但是如何知道用户是否打算输入一个新字符来命令read()等待用户的输入?

因此,我会说你不能做你想做的事,至少据我所知,用一种简单的方法。你可以让你的程序将stale输入提供给stdin,这样你的程序就有了读取用户输入的印象。但是,如果用户实际输入了新的输入,则程序应仔细处理该情况。

+0

是的,但打印时?如果你被阻止等待stdin的输入,那么你不会每秒都做一些事情。 –

+0

正确@BoundaryImposition,因为他/她的函数有'getchar()',它会一直挂起! – gsamaras

+0

感谢您的帮助。我现在有一个解决方案,在我的文章中编辑。 – Fleksiu

0

您可以设置SIGALARM处理器,x秒后设置报警和显示的内容的getchar在处理程序返回