Is there a way to get user input without pressing

2020-03-01 10:04发布

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

标签: c++ input
2条回答
闹够了就滚
2楼-- · 2020-03-01 10:28

you can use conio.h library and a function _getch() to get input in a live fashion and you can also set loop for multiple inputs.

#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();
    }
}
查看更多
smile是对你的礼貌
3楼-- · 2020-03-01 10:32

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.

reference: http://shtrom.ssji.net/skb/getc.html

查看更多
登录 后发表回答