Return pressed key without enter for confirmation

旧城冷巷雨未停 提交于 2019-12-11 18:52:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!