【问题标题】:Display something every x seconds with different output每 x 秒以不同的输出显示一些东西
【发布时间】: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


【解决方案1】:

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()等待用户输入呢?

因此,我会说你不能做你想做的事,至少据我所知,用简单的方法。您可以让您的程序将过时的输入提供给标准输入,这样您的程序就会产生读取用户输入的印象。但是,如果用户实际输入了新的输入,您的程序应该小心处理这种情况。

【讨论】:

  • 是的,但是什么时候打印?如果您在等待来自标准输入的输入时被阻止,那么您不是每秒都在做某事。
  • 正是@BoundaryImposition,因为他/她的函数有getchar(),所以它会一直挂着!
  • 感谢您的帮助。我现在有一个解决方案,在我的帖子中进行了编辑。
  • 为避免getchar() 的挂起,请使用第一个答案:http://stackoverflow.com/questions/22166074/is-there-a-way-to-detect-if-a-key-has-been-pressed
  • 太棒了@Fleksiu! user3629249 您可以使用 [链接](www.google.gr)。但符号反之亦然!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多