问题
I've searched for a while to find a function in Windows systems to use in C programming, to determine which key was pressed, without requiring the 'enter' key for confirmation.
I've found kbhit()
, but this only returns positive on key press, and 0 while no key-press. I'd like the same behavior on a function, but returning my key's ASCII code.
The reason is that I want to build some controls, on a console-based game, where I need arrows to navigate the player. 'A' would move my point left, 'D' right.
At this moment, I need to press 'a' and 'enter,' 'd' and 'enter,' with the simple scanf("%c")
, and would be nice if the console would react only if pressing a letter instead of a+enter on every movement.
回答1:
Look at this:
char ch;
ch = getch();
if(ch == 's') printf("you pressed s \n");
回答2:
From the sound of things you want something like this:
#include <conio.h>
int ch;
if (kbhit())
ch = getch();
getch()
blocks waiting for input, but it will read a single keystroke without buffering, so it doesn't wait for you to press the enter key.
来源:https://stackoverflow.com/questions/9740717/return-pressed-key-without-enter-for-confirmation