0
我有一个简单的程序,需要输入一个时间和消息,并在每个时间间隔输出一条消息。我遇到的问题是,当用户尝试输入一个新的定时器并且之前的定时器显示它的消息时,它会打乱输入。如何在命令行中分离输出和输入?
我想知道如何为输入和输出制作单独的字段,因此它们不会重叠。程序的语言是C,我在网上找不到任何东西。
我有一个简单的程序,需要输入一个时间和消息,并在每个时间间隔输出一条消息。我遇到的问题是,当用户尝试输入一个新的定时器并且之前的定时器显示它的消息时,它会打乱输入。如何在命令行中分离输出和输入?
我想知道如何为输入和输出制作单独的字段,因此它们不会重叠。程序的语言是C,我在网上找不到任何东西。
取决于您想要的便携性以及您的目标平台。
对于非常简单的应用ANSI escape codes就足够了。否则看看库(ncurses是强大的),tput
(如果你在* NIX)等等。
如果您决定玩控制台代码,请记住echo -e "\033c"
(通常)将所有终端设置重置为默认值。
这是一个粗略的(Linux)示例,它使用ANSI转义来显示时钟和最后一条命令。为了简单起见,使用SIGALRM
。
关于主题here还有更多。
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <unistd.h> /* alarm() */
int lines = 3; /* Store how many lines we have. */
/* Print current time every second at first line.. */
void prnt_clock()
{
time_t tt;
struct tm *tm;
char buf[80];
time(&tt);
tm = localtime(&tt);
strftime(buf, sizeof(buf), "%H:%M:%S", tm);
fprintf(stdout,
"\033[s" /* Save cursor position. */
"\033[%dA" /* Move cursor up d lines. */
"\r" /* Moves cursor to beginning of line. */
"%s" /* String to print. */
"\033[u" /* Restore cursor position. */
,
lines,
buf
);
fflush(stdout);
alarm(1);
}
/* Print last command entered at third line. */
void prnt_cmd(char *cmd)
{
fprintf(stdout,
"\033[s\033[%dA\r\033[KLast cmd: %s\033[u",
lines - 2, cmd
);
fflush(stdout);
}
/* Empty the stdin line */
void process_input(char c)
{
char buf[32];
int i = 0;
++lines;
while (c != '\n' && i < 31) {
buf[i++] = c;
c = getchar();
}
buf[i] = 0x00;
if (c != '\n')
while (getchar() != '\n')
;
prnt_cmd(buf);
}
/* Signal handler. */
void sig_alarm(int sig)
{
if (sig == SIGALRM) {
signal(SIGALRM, SIG_IGN);
prnt_clock();
signal(SIGALRM, sig_alarm);
}
}
int main(void /* int argc, char *argv[] */)
{
char prompt[16] = "\033[1;31m$\033[0m "; /* We want bold red $ */
int c;
signal(SIGALRM, sig_alarm);
fprintf(stdout,
"\n" /* line for clock (line 1.)*/
"---------------------------------------------------\n"
"Enter q to quit.\n" /* line for status (line 3.) */
"%s" /* prompt (line 4+) */
,
prompt
);
prnt_clock();
while (1) {
c = getchar();
if (c == 'q')
break;
process_input(c);
fprintf(stdout, "%s", prompt);
fflush(stdout);
}
return 0;
}
欢迎来到Stack Overflow。请尽快阅读[关于]页面。根据你的描述,你似乎在寻找一个系统,如果你有一个程序,称之为'dribbler',它每隔一秒钟向标准输出写入一条消息,然后在后台运行它,然后让用户输入另一个命令:鉴于这种情况,当用户输入未读的输入时,您不希望'dribbler'写入。是对的吗?如果是这样,那么做到这一点并不难。我能想到的最接近的方法是SIGTTOU信号,它在写入终端时暂停进程,但不是前台进程。 –
如果你想要实际的单独的*字段*,那么你需要类似UNIX的系统的'ncurses'或者更普遍的一些其他终端处理库。 –