Getting input from console without cin?
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
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.
#include <stdio.h>
#include <conio.h>
int main()
{
while(1)
{
clearScreen();
if(kbhit())
{
int const ch = getch();
switch(ch)
{
case 0x61: printf("A was pressed!\n"); break;
case 0x64: printf("D was pressed!\n"); break;
}
}
restThread(100);
}
return 0;
}
精彩评论