2
我在终端上做了一个简单的2D游戏,我一直想知道如何得到stdin而不必返回。因此,用户不必按w \ n(\ n返回),他们只需按'w'即可前进。 scanf,gets和getchar不能做到这一点,但我已经看到它在诸如Vi之类的程序中完成。我将如何实现这一目标?在没有 n的情况下捕获输入 n
我在终端上做了一个简单的2D游戏,我一直想知道如何得到stdin而不必返回。因此,用户不必按w \ n(\ n返回),他们只需按'w'即可前进。 scanf,gets和getchar不能做到这一点,但我已经看到它在诸如Vi之类的程序中完成。我将如何实现这一目标?在没有 n的情况下捕获输入 n
您需要将终端设置为非规范模式。您可以使用像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.
我要去寻找到这一点,但是这看起来像一个好办法做到这一点。 – user1150512 2012-04-14 09:30:19