【问题标题】:Is there a way to get user input without pressing the enter key?有没有办法在不按回车键的情况下获取用户输入?
【发布时间】:2012-03-03 16:51:56
【问题描述】:

我正在编写一个控制台游戏(pac-man),我想知道如何在没有用户按下回车键的情况下获得用户输入。我在互联网上浏览了一下,发现了一些关于_getch() 的东西,但它显然不再是最新的,并且没有头文件可以声明它,除非有人构建自己的,我不能这样做,因为我对 C++ 还是很陌生. 那么我将如何构建一个可以做到这一点的代码呢? 谢谢

【问题讨论】:

标签: c++ input


【解决方案1】:

这对我有用(我在 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;
}

它使控制台无缓冲。

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

【讨论】:

    【解决方案2】:

    您可以使用 conio.h 库和函数 _getch() 以实时方式获取输入,还可以为多个输入设置循环。

    #include<conio.h>
    #include<iostream>
    using namespace std;
    int main()
    {
        char n = 'a'; //Just to initialize it. 
        while(n != 'e') // Will exit if you press e.
        {
            n = _getch();
        }
    }
    

    【讨论】:

    • conio.h 只存在于 WIN cmd
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2011-06-04
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多