Hey,
I have a really simple problem, but for some reason can't work it out!
I just want a loop to keep repeating itself with no user input forever, or until the user presses enter, or enters another key.
Any suggestions?
Thanks
Printable View
Hey,
I have a really simple problem, but for some reason can't work it out!
I just want a loop to keep repeating itself with no user input forever, or until the user presses enter, or enters another key.
Any suggestions?
Thanks
I believe there's a stream function that peaks at a stream to see if there is anything in the buffer. You could then in an loop check if there is a character in cin, as you print one character at a time to cout. Just be sure that autoflush is on, or that you flush after each character is printed.
EDIT: found it: streambuf::in_avail. You'll need to call cin.rdbuf() to get the buffer.
if you are just waiting for the user to press enter, this is a bad idea, because your program will be using 100% cpu in the empty loop. Block for input instead. That way processor time is yielded to other processes.
The next-best solution is just to sleep 20 or 30 ms or so between each check to minimize cpu use.
It still won't work, because in_avail() only checks the stream's internal buffer in most implementations. Even when the user gives input and hits enter, this buffer won't change until an actual read is attempted.
You need platform-specific functionality for this.