解决 ncurses wgetch() 若一直按住按键,则程序崩溃退出问题

73 阅读1分钟

现象

在 while 中,循环处理按键,采用 wgetch() 函数获取键盘输入,然后分支处理;若一直按住按键,用不了多久,程序就会莫名其妙的崩溃退出。

解决过程

思来想去,我想到若一直按住按键,会产生大量的按键事件,由于来不及处理,会导致内存不够,进而崩溃,若能清除多余的按键事件就好了。

发现这个函数

 NAME

flushinp - discard input

 SYNOPSIS



#include <curses.h>

int flushinp(void);

 DESCRIPTION

The flushinp()  function discards (flushes) any characters in the input buffer associated with the current screen.

 RETURN VALUE

The flushinp()  function always returns OK.

 ERRORS

No errors are defined.

 SEE ALSO

<curses.h> .

在 wgetch() 获取一个字符后,就调用 flushinp() 清空残留的按键事件,但仍不起作用。

后来发现,还要设置 无缓冲模式 cbreak() 才能解决该问题。