Learn to Code via Tutorials on Repl.it!

← Back to all posts
Detecting keypresses in c++ without pressing enter
RomeroSchwarz

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

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

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.

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.

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

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.

Voters
CooperSmith1
asterishk
Atias
JennyHomann
lucaslbc
WILLIAMBAEWER
3A28_Su_Shu_Shi
braxtondb
NoahRider67
MatthewWesolows
Comments
hotnewtop
ChimaNwosu1

Hey do you have any advice on how I can use this code to make a d- pad. So like when I press wsad instead it prints out a space to the right, left, down, or up instead of an integer?

MatthewWesolows

@ChimaNwosu1 use a switch statement: https://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm
you can get the actual char key press by casting it like so:
int key = keypress();
std::cout << (char)key << std::endl;

Highwayman

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

@Highwayman Thanks, that works much better.

Highwayman
Highwayman

@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

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

Highwayman

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

mwilki7

I think back ticks ` should replace the apostraphes ' for the code to show up

RomeroSchwarz

@mwilki7 yeah just fixed that, my bad

Bunnytoes

how do you do this in c#?

jhonnyisraelisr

You´re my hero!