Ask coding questions

← Back to all posts
Input Getters
JustinWu (8)

I created this incredibly basic game which uses inputs to move the character around. Does c++ provide something which allows the console to automatically know what the person has inputted? If not, are there any methods that could allow that?

Answered by ANDREWVOSS (187) [earned 5 cycles]
View Answer
#include <unistd.h>
#include <termios.h>

char getch() {
  char buf = 0;
  struct termios old = {0};
  if (tcgetattr(0, &old) < 0)
  old.c_lflag &= ~ICANON;
  old.c_lflag &= ~ECHO;
  old.c_cc[VMIN] = 1;
  old.c_cc[VTIME] = 0;
  if (tcsetattr(0, TCSANOW, &old) < 0)
    perror("tcsetattr ICANON");
  if (read(0, &buf, 1) < 0)
    perror ("read()");
  old.c_lflag |= ICANON;
  old.c_lflag |= ECHO;
  if (tcsetattr(0, TCSADRAIN, &old) < 0)
    perror ("tcsetattr ~ICANON");
  return (buf);

Just use the getch() function and it will return whatever letter key the user is currently pressing.

JustinWu (8)

Can you explain how this works? It seems really obscure (or I still suck at programming)


@JustinWu I'm not entirely sure how it works, if I'm being honest.