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

11 c++ input

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

Jör*_*yer 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;
}
Run Code Online (Sandbox Code Playgroud)

它使控制台无缓冲.

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


小智 5

您可以使用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)