【问题标题】:Capturing input without \n在没有 \n 的情况下捕获输入
【发布时间】:2012-04-26 11:59:11
【问题描述】:

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

【问题讨论】:

    标签: c input terminal


    【解决方案1】:

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

    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 documentation. 特别是this part.

    【讨论】:

    • 我打算研究一下,但这看起来是个不错的方法。
    猜你喜欢
    • 2012-02-24
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2014-04-12
    • 1970-01-01
    • 2020-06-02
    相关资源
    最近更新 更多