【问题标题】:How I can get input without press enter end without see the input on screen?如何在不按 enter end 而在屏幕上看到输入的情况下获得输入?
【发布时间】:2020-07-14 12:49:00
【问题描述】:

我想创建一个简单的游戏,其中使用“WASD”在屏幕上移动对象。问题是getchar 无需按回车即可工作,但如果不显示在屏幕上则不会接受输入。我该如何解决?

PS:程序是C语言,在Linux终端上。

//my code:
while(1){
    input = getchar();
    if(input == 'a'){/*do something*/}
    if(input == 'd'){/*do something*/}
    //...
}

【问题讨论】:

标签: c linux terminal


【解决方案1】:

由于你是在 Linux 上,你可以使用termios.h,这里模拟旧的getch (conio.h):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>

static struct termios term, oterm;

static int getch(void)
{
    int c = 0;

    tcgetattr(0, &oterm);
    memcpy(&term, &oterm, sizeof(term));
    term.c_lflag &= ~(ICANON | ECHO);
    term.c_cc[VMIN] = 1;
    term.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &term);
    c = getchar();
    tcsetattr(0, TCSANOW, &oterm);
    return c;
}

int main(void)
{
    puts("Press Q to exit");
    while (1) {
        int c = getch();

        switch (c)
        {
            case 'A':
            case 'a':
                puts("A was pressed");
                break;
            case 'D':
            case 'd':
                puts("D was pressed");
                break;
            /* ...*/
            case 'Q':
            case 'q':
                exit(EXIT_SUCCESS);
            default:
                break;
        }
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多