有没有办法在不按回车键的情况下获得用户输入?

时间:2012-03-03 16:51:57

标签: c++ input

我正在编写一个控制台游戏,(pac-man),我想知道如果没有他们按下回车键我会得到用户输入。我稍微环顾了一下互联网,我找到了一些关于_getch()的东西,但它显然不再是最新的,并且没有头文件可以声明它,除非一个人构建他自己的,我不能做,因为我还是新的到C ++。 那么我将如何构建可以执行此操作的代码? 谢谢

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:3)

您可以使用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();
}
}
相关问题