I'm trying to make a little console program that will basically be console pong. So right now I have this:
int main()
{
while(1)
{
clearScreen();
restThread(100);
}
return 0;
}
The only input I need to poll is if the user has pressed the A or D key since the screen was cleared. I will also need to know when the key is released. I'm also trying to do this cross platform.
so really all I need is like an if(keyWasDown('a')) {} sort of function.
Thanks
The standard C++ I/O libraries only have functions that read input from a stream, which means to get a string on a console, enter key should be pressed. If you want to get the input without pressing enter key, you have to use nonstandard functions like _getch() in <conio. h> in Windows.
The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source.
It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
The cin function would return false if there is no more lines for input. You can do the following to read until the end of input, or eof if you are redirecting cin to read from a file. You could do freopen("filename", "r",m stdin); to redirect the input.
Maybe you want kbhit (non-blocking) or getch (blocking), both from <conio.h>
. There's also getchar, from <stdio.h>
or <cstdio>
.
If you want the program to wait for a keyboard press, getch
or getchar
by themselves will do.
If you don't want the program to wait for a keyboard press, kbhit
combined with either getch
or getchar
will suffice.
However, as GMan said, these methods are not really cross platform (if you never intend to try this on different platforms, that's moot, really). For console games, you might be interested looking into ncurses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With