Detecting keypresses in c++ without pressing enter
RomeroSchwarz (262)

So, in all of the repl consoles, you need to press enter to input something. However, there are ways around this. This one is for c++.

First, we're going to need a few things, specifically iostream, stdio, and stdlib

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

Next, we're going to make a function that'll return whatever key is pressed. I'll call it keypress for readability.

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

int keypress() {

}

Now here's the confusing part. We're going to change how the console works. I myself don't fully understand it, but the basic premise is that we change how we input at the beginning of the function, and reset it at the end.

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

int keypress() {
  system ("/bin/stty raw");

  //code will go here

  system ("/bin/stty cooked");
}

Now, we'll create a variable (c) to store the ASCII value of the key pressed, and give it a value by taking input with getc from stdin, then return the value.

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

int keypress() {
  system ("/bin/stty raw");
  int c;
  c = getc(stdin);
  system ("/bin/stty cooked");
  return c;
}

Finally, we'll make sure the key that is pressed isn't visible to the user by disabling and reenabling echo.

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

int keypress() {
  system ("/bin/stty raw");
  int c;
  system ("/bin/stty -echo")
  c = getc(stdin);
  system ("/bin/stty echo")
  system ("/bin/stty cooked");
  return c;
}

And that's it!

Below is a repl that demonstrates this. Try it out by pressing a key, and the console will display the ASCII value of the key.

You are viewing a single comment. View All
Highwayman (989)

Nice! If you want you can also turn off echo using /bin/stty -echo just so they don’t have to clear the entire console each time.

RomeroSchwarz (262)

@Highwayman Thanks, that works much better.

Highwayman (989)

@RomeroSchwarz oh also, you can just use /bin/stty sane if you want to return the console’s input to it’s default settings. It’ll shorten the code a little and make it a little more understandable too.

RomeroSchwarz (262)

@Highwayman maybe you should've made this tutorial instead of me!

Highwayman (989)

@RomeroSchwarz lol nah, I’m not good at tutorials.