0

I want to output the ASCII Code of the last key I pressed, every x second.

As example:

If i press a(97), the terminal should show the 97 every x second. When I now press the w(119), the program now should print the 119 instead of the 97. So far my program just prints the first key I've pressed.

Here are the main and the other method:

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");
}

EDIT:

With a little bit of testing i've now a method which solves my problem

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();
}
Fleksiu
  • 191
  • 1
  • 10

2 Answers2

0

getchar() waits for only one character, so this:

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

causes this behavior. You read one character, you print it in movePlayer(). Then you flush the output buffer and go to sleep. Then you just repeat, which means that you have to input again.

Store the input and print it again, if you wish. However, your function will always wait for new input to arrive.


Here is an attempt with read() as suggested, but it will have similar behavior to your code as it is now:

#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");
}

Please read read() from stdin to go on. You can tell read() for how many characters to wait and then return, but how will you know if the user intends to input a new character to command read() to wait for user's input?

As a result, I would say that you can not do what you wish, at least as far as I can tell, with a simple approach. You could have your program feed the stale input to stdin, so that your program has the impression it reads user's input. However, in case the user actually inputs fresh input, your program should handle that case carefully.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

You can setup SIGALARM handler, setup alarm after x seconds and display what getchar returns in handler

Pras
  • 4,047
  • 10
  • 20