捕获输入而不\n

标签 c input terminal

我正在终端中制作一个简单的 2d 游戏,我一直想知道如何获得标准输入而无需返回。因此,用户无需按 w\n(\n 用于返回),只需按“w”即可前进。 scanf、gets 和 getchar 无法做到这一点,但我以前见过 Vi 等程序中可以做到这一点。我该如何实现这一目标?

最佳答案

您需要将终端设置为非规范模式。您可以使用 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.

关于捕获输入而不\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10152381/

相关文章:

c - 为什么这个 C 函数在 fclose 时崩溃?

c - 当我扫描一个数组时,它会更改另一个数组吗?

c - 如何等待非子进程退出

windows - winapi中的简单鼠标移动检测(但没有光标移动)

c - 越界数组和段错误

c++ - 如何将文件中的数据存储到具有 vector 成员的结构 vector 中

C++ 调试断言错误

terminal - 使用 tmux 在终端中进行鼠标滚动和选择

python - 如何在 Python 中只查找总 RAM

linux - VSCode,如何更改默认终端?