聆听按键,而不会使整个程序停在C中 [英] Listen for a keypress without stalling the entire program in C

查看:51
本文介绍了聆听按键,而不会使整个程序停在C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个游戏,当按下某些键时对象会移动.但是我想实现它,以便东西一直在移动,循环一直在运行.到目前为止,诸如scanf和getchar之类的键盘输入功能都在等待我按下一个键,直到它们允许程序继续执行.如何在不停止程序的情况下(不使用线程)监听按键?

I'm trying to make a game where objects move when certain keys have been pressed. But I want to implement it so that stuff is moving and loops are running all the time. So far the keyboard input functions such as scanf and getchar have all been waiting for me to press a key until they allow the program to continue. How do i listen for key presses without stalling the program (without using threads)?

推荐答案

有一种使用循环实现此方法的方法.
以下程序将循环执行其他操作,并且在每遍操作中都将检查是否已按下某个键.然后,按下的键将存储到变量 c .

There is a way of implementing this using a loop.
The following program will do something else in a loop, and in every pass it will check if a key has been pressed. The pressed key will then be stored to a variable c.

#include <stdio.h>
#include <conio.h>

int main(void) {
    char c = '\0';

    while (1) { 
        if (kbhit()) { 
            c = getch(); 
        }
        /* If a key has been pressed */
        if (c != '\0') {
            /* Do something */
            c = '\0'; // and put it back to \0
        }

        /* Do something else */
    }

    return 0;
}

注意:此解决方案仅在Windows和其他可以包含头文件" conio.h "的操作系统上起作用

Note: This solution works only on Windows and other operating systems where the header file "conio.h" can be included

这篇关于聆听按键,而不会使整个程序停在C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆