我有一个使用ncurses(C ++)读取表单字段的代码,但是当表单字段未完全输入时,我无法显示值。
#include <form.h>
#include <curses.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
WINDOW *chatwin, *entrywin;
FIELD *field[1];
FORM *fo;
void quit(void)
{
int i;
unpost_form(fo);
free_form(fo);
free_field(field[0]);
free_field(field[1]);
delwin(chatwin);
endwin();
}
int main(void)
{
int xsize, ysize;
int charinput, i;
char inputstring[200];
char ttime[10];
initscr();
atexit(quit);
clear();
noecho();
curs_set(1);
cbreak();
keypad(stdscr, TRUE);
getmaxyx(stdscr, ysize, xsize);
start_color();
use_default_colors();
init_pair(1, COLOR_YELLOW, COLOR_BLUE);
init_pair(2, COLOR_BLUE, COLOR_WHITE);
chatwin = newwin((ysize - 8), (xsize-21), 6, 21);
entrywin = newwin(1, (xsize-21), (ysize - 1), 21);
field[0] = new_field(1, (xsize - 21), 0, 0, 0, 10);
field[1] = 0;
set_form_win(fo, entrywin);
fo = new_form(field);
post_form(fo);
field_opts_on(field[0], O_STATIC);
set_field_fore(field[0], COLOR_PAIR(2));
set_field_back(field[0], COLOR_PAIR(2));
refresh();
wrefresh(chatwin);
wrefresh(entrywin);
while((charinput=getch()) != KEY_END)
{
switch(charinput)
{
case 10:
snprintf(inputstring, 200, "%s", field_buffer(field[0], 0));
struct tm *akttime;
time_t second;
time(&second);
akttime = localtime(&second);
strftime(ttime, 10, "%H:%M:%S", akttime);
wprintw(chatwin, "<%s> %s|\n", ttime, inputstring);
wrefresh(chatwin);
set_field_buffer(field[0], 0, "");
wrefresh(entrywin);
break;
default:
form_driver(fo, charinput);
wrefresh(entrywin);
}
}
return(0);
}
输出
Obs。:输入第二行: ejheeh ,但输出为空
<02:31:42> dddddddkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
kkkkkkkkkkk|
<02:31:45>
|
<02:31:51> ddddddddddddddddddddddddddddddddddddddddddddddddddddfffffff
fffffffffff|
答案 0 :(得分:5)
通常,ncurses表单库在离开字段之前不会同步字段缓冲区。由于您在离开字段之前尝试读取缓冲区,因此缓冲区没有当前内容。
强制缓冲区同步而不实际移动到下一个字段的一种简单方法是强制字段验证 - 这将同步然后运行任何验证函数。
在case 10:
form_driver(fo, REQ_VALIDATION);
您可能想要检查验证错误:
if (form_driver(fo, REQ_VALIDATION) != E_OK) {
// do something
}