我正在终端中制作一个简单的 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 文档。 http://www.gnu.org/software/libc/manual/html_node/Low_002dLevel-Terminal-Interface.html#Low_002dLevel-Terminal-Interface尤其这部分。 http://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html#Canonical-or-Not
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)