我编写了一个小程序,我可以在其中上下左右移动光标。
现在我要添加的最后一件事是光标到达屏幕边缘时跳转到下一个或上一个的能力。
因为我已经实现了各种检查以确保我可以在 key_up 和 key_down 输入句柄部分中上下移动,所以我想“借用”这些。我当然可以重写它们并在 key_left 和 key_right 场景中重用它们。
但是,如果我可以像按下 key_up 或 key_down 一样写入 stdin 和“假”用户输入,并且只需要更改光标的 x 位置,那么它会更短。
所以我想要这样的东西
putc(KEY_UP,stdin);fseek(stdin,-1, SEEK_CUR);
所以在下一个 getch() 中它会检索我用 putc 放入标准输入的字符!
整个程序界面我都使用ncurses!
根据 Filipe 的建议,我尝试使用 ungetc() 做一些事情,但它没有我想要的行为。
这是一个小测试程序,理论上它应该在第一个字符后打印出无限个 p,但它没有:
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
int main () {
int input,i=0;
initscr();
start_color();
keypad(stdscr, TRUE);
raw();
nonl();
noecho();
do {
input=getch();
if (i==24) {i=0;erase();}
mvprintw(i,0,"%c --- %i",input,input);
refresh();
if (ungetc((unsigned char)'p', stdin)==EOF) {
printw(" ERROR UNGETC");
}
else {printw(" SUCCES UNGETC");}
++i;
} while (input!='q');
endwin();
exit(2);
}
最佳答案
由于您使用的是 ncurses,因此您正在寻找 ungetch()
。从联机帮助页:
The ungetch routine places ch back onto the input queue to be returned by the next call to wgetch. There is just one input queue for all windows.
函数原型(prototype):
int ungetch(int ch);
它在失败时返回整数 ERR
和 ERR
以外的整数值(OK
在 ungetch() 的情况下
) 成功完成后。
仅供日后引用
如果阅读此答案的任何人想要一种将字符推回文件流的简单方法,ungetc()
是正确的方法。 ungetch()
仅适用于任何使用 ncurses 的人。
ungetc()
将一个字符推回到给定的文件流中:
int ungetc(int c, FILE *stream);
来自手册页:
ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.
您需要使用 stdin
调用它,如下所示:
ungetc((unsigned char) KEY_UP, stdin);
成功时返回c
,错误时返回EOF
。请记住,它只能保证一个推回字符;您不能调用 ungetc()
两次,然后期望调用 getch()
两次可以返回最后 2 个推送的字符。
关于c - 写入标准输入,然后将流移回 1 个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21727239/