【发布时间】:2017-05-06 16:06:52
【问题描述】:
我想每隔 x 秒输出一次我按下的最后一个键的 ASCII 码。
例如:
如果我按 a(97),终端应该每隔 x 秒显示 97。当我现在按下 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();
}
【问题讨论】:
-
这是因为
getchar只等待一个字符;你必须改用read。
标签: c while-loop ascii