有没有一种方法可以在不按Enter键的情况下获取用户输入? [英] Is there a way to get user input without pressing the enter key?

查看:81
本文介绍了有没有一种方法可以在不按Enter键的情况下获取用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个控制台游戏(吃豆人),我想知道如果不按Enter键就如何获得用户输入.我环顾了一下互联网,发现了一些有关_getch()的东西,但显然不再存在,并且没有头文件可以声明它,除非有人自己构建,我不能做,因为我对C ++还是很陌生. 那么我将如何构建一个可以做到这一点的代码呢? 谢谢

I'm programming a console game, (pac-man), and I was wondering how I would get user input without them pressing the enter key. I looked around the internet a little and I found some stuff about _getch() but it is apparently no longer current and no header files are known to declare it unless one builds his own which I cannot do as I'm still really new to C++. So how would I build a code that can do this? Thanks

推荐答案

这对我有用(我在Linux上):

This works for me (I am on linux):

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

int main()
{
    struct termios old_tio, new_tio;
    unsigned char c;

    /* get the terminal settings for stdin */
    tcgetattr(STDIN_FILENO,&old_tio);

    /* we want to keep the old setting to restore them a the end */
    new_tio=old_tio;

    /* disable canonical mode (buffered i/o) and local echo */
    new_tio.c_lflag &=(~ICANON & ~ECHO);

    /* set the new settings immediately */
    tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);

    do {
         c=getchar();
         printf("%d ",c);
    } while(c!='q');

    /* restore the former settings */
    tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);

    return 0;
}

它使控制台没有缓冲.

It makes the console unbuffered.

参考: http://shtrom.ssji.net/skb/getc.html

这篇关于有没有一种方法可以在不按Enter键的情况下获取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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