我正在编写一个没有 ncurses 的小型 cli 程序,但我遇到了一个问题。 我使用转义序列来查询光标位置,当用户没有输入或输入很少时,这可以正常工作,但是当用户输入频率很高时,这会污染我的查询响应。
我使用 read 来处理这样的用户输入:
read(0, &c, sizeof(c))
我使用 printf/scanf 来处理转义序列查询,如下所示:
printf("\033[6n");
scanf("\033[%d;%dR", y, x);
为了解决这个问题,我尝试在每次读取后获取光标位置。当我继续按某个键(例如“z”)时,我在 printf 和 scanf 之间收到一些 z,因此 scanf 失败。 我期望用户输入在查询期间被阻止或缓冲,但不是:(。
查询后,我可以在 scanf 和缓冲区输入之前搜索 stdin 流上的序列,但相当繁重,并且不是 100% 确定。
有没有一个简单的解决方案可以解决这个问题? (保证顺序、查询前阻止用户输入等...)
编辑于2014-07-01 21:21:
我创建了一个小样本来解决这个问题。 标准键没有问题,但是UP键,或者HOME键污染了printf/scanf查询序列...
// Build gcc -o test main.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
char getch();
void get_cursor_pos(int* x, int* y);
void reset_terminal_mode();
struct termios g_termios;
int main(int arc, char** argv)
{
char c;
int x,y;
struct termios new_termios;
printf("TEST STDOUT/STDIN QUERY\n");
// Setting raw terminal
printf("Setting raw terminal mode...\n");
tcgetattr(0, &g_termios);
memcpy(&new_termios, &g_termios, sizeof(struct termios));
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
new_termios.c_oflag |= OPOST|ONLCR;
tcsetattr(0, TCSANOW, &new_termios);
// Main loop
printf("Starting main loop...\n");
printf("(Press [=] to abort)\n");
do{
c=getch();
printf("0x%02X",c);
get_cursor_pos(&x,&y);
printf("<%dx%d> ",x,y);
}while(c!='=');
// End loop
printf("\nEnd\n");
return EXIT_SUCCESS;
}
char getch()
{
char c;
read(0, &c, sizeof(c));
return c;
}
void get_cursor_pos(int* x, int* y)
{
*x=0;
*y=0;
printf("\033[6n");
scanf("\033[%d;%dR", y, x);
}
void reset_terminal_mode()
{
printf("Reset terminal mode...\n");
tcsetattr(0, TCSANOW, &g_termios);
}
你能解释一下什么是append吗?
提前致谢
最佳答案
您不能使用 getch()
(如所写)来捕获 Home
或 Arrow
键,因为键码是 多字节代码。您必须更改 getch()
函数来处理单字节和多字节输入,以捕获使用多字节代码的键。请参阅Unicode in C/C++获取处理多字节输入的例程的相当详尽的解释和示例。
关于c - C 程序中的 stdout 转义查询和 stdin 冲突(无 ncurses),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24497756/