不使用\ n捕获输入 [英] Capturing input without \n

查看:50
本文介绍了不使用\ n捕获输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在终端中制作一个简单的2D游戏,我一直想知道如何在无需返回的情况下获得标准输入.因此,无需用户按下w \ n(返回\ n),他们只需按下'w',它就会前进.scanf,gets和getchar无法做到这一点,但是我已经看过以前在诸如Vi之类的程序中做到这一点.我将如何实现呢?

I am making a simple 2d game in the terminal, and I have been wondering how I could get stdin without having to return. So, instead of the user having to press w\n (\n for return), they would just press 'w' and it would go forwards. scanf, gets, and getchar cannot do this, but I have seen it be done before in programs such as Vi. How would I achieve this?

推荐答案

您需要将终端设置为非规范模式.您可以使用tcsetattr和tcgetattr之类的函数来设置和获取终端属性.这是一个简单的示例:

You need to set your terminal to non-canonical mode. You can use functions like tcsetattr, and tcgetattr to set and get terminal attributes. Here is a trivial example:

int main(int argc, const char *argv[])
{
    struct termios old, new;
    if (tcgetattr(fileno(stdin), &old) != 0) // get terminal attributes
        return 1;

    new = old;
    new.c_lflag &= ~ICANON; // turn off canonical bit.
    if (tcsetattr(fileno(stdin), TCSAFLUSH, &new) != 0) // set terminal attributes
        return 1;

    // at this point, you can read terminal without user needing to
    // press return

    tcsetattr(fileno(stdin), TCSAFLUSH, &old); // restore terminal when you are done.

    return 0;
}

有关这些功能的更多信息,请参见 glibc文档.特别是这部分.

For more info about these functions, see glibc documentation. Especially this part.

这篇关于不使用\ n捕获输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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