Skip to content
Sign upLog in
← Back to Community

Getting input without stopping code (preferably in c++)

Profile icon
roysun

I am currently working on a text game where people have to type stuff to react to events written in the console. There is a main loop that constantly updates what is written in the console. Also,the time factor here is important (the faster the user reacts and types the better it is for them).

So is there a way to get input without stoping the loop in c++? If not, I am willing to learn another language for this purpose (am looking for one anyways). Thanks!

Answered by theangryepicbanana [earned 5 cycles]
View Answer
Voters
Profile icon
LeytonBammel
Profile icon
roysun
Comments
hotnewtop
Profile icon
theangryepicbanana

link to project?

Profile icon
roysun

@theangryepicbanana
Oh, just got the idea and started it, but realized that I was stuck here.... I could link it but there's literally nothing there....

Profile icon
theangryepicbanana

@roysun
ok well after looking, it seems as though you will need to use something like conio.h to get "unbuffered" input

Profile icon
roysun

@theangryepicbanana
Unfortunately, it seems that conio.h does not work on repl.it with c++. Some source say it is not compatible with c++ while other forums say they are usable in c++ (with windows). Do you know if there is anything that can accomplish this in Ruby? I started coding by learning a bit of ruby.

Profile icon
theangryepicbanana

@roysun
Yes! I have done this in Ruby in the past when making games. The first thing you will need is is to put require 'io/console' at the top of your code (this will import something needed in the next step). The second thing you need yo do is to add this method:

def readChar STDIN.echo = false STDIN.raw! input = STDIN.getc.chr if input == "\e" input << STDIN.read_nonblock(3) rescue nil input << STDIN.read_nonblock(2) rescue nil end ensure STDIN.echo = true STDIN.cooked! return input end

This method can read a key press from the terminal without needing to press enter. The third thing you will need to do is to make 2 threads. The first one will look something like this:

get_key_event = Thread.new do loop do @key = readChar next end end

This will repeatedly wait for keyboard input. The other thread will be your main loop, and will look something like:

main_loop = Thread.new do loop do # game stuff end end

Finally, you need to add

get_key_event.join main_loop.join

at the end of your code to make it run. After that, you're done! (please mark this comment as "best answer" if this helped)

Profile icon
roysun

@theangryepicbanana
Thanks! I'm going to dive back into my ruby pdf and test it out!

Profile icon
theangryepicbanana

@roysun
ye glad to help