欣赏
首先,我非常感谢Sam Varshavchik
我发现的主要结果
Sam 给了我使用Curses Library 的提示。我阅读了文档,现在完成了基本功能。
我的方法是创建子窗口(output_win 和 input_win)。用户输入显示在input_win,而程序信息打印在output_win。
让我分享我的代码:
#include <iostream>
#include <string>
#include <curses.h>
#include <thread>
#include <atomic>
#include <chrono>
#include <unistd.h>
using namespace std;
WINDOW* win;
WINDOW* output_win;
WINDOW* input_win;
int row = 0, col = 0;
std::atomic<bool> flag(false);
string buf;
void ninit()
{
win = initscr();
getmaxyx(win, row, col);
cbreak();
noecho();
nonl();
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);
refresh();
}
void nprintf(string str)
{
touchwin(win);
str += '\n';
wprintw(output_win, str.c_str());
wrefresh(output_win);
}
void nprintf(const char* fmt, ...)
{
touchwin(win);
va_list ap;
va_start(ap, fmt);
vw_printw(output_win, fmt, ap);
va_end(ap);
wrefresh(output_win);
}
void nmonitor()
{
while(1)
{
char x = getch();
if(x != '\r')
{
touchwin(win);
buf += x;
waddch(input_win, x);
}
else
{
nprintf(buf);
touchwin(input_win);
flag = true;
wclear(input_win);
}
wrefresh(input_win);
}
}
string nget()
{
while(!flag)
usleep(100);
string cmd = buf;
flag = false;
buf = "";
return cmd;
}
////////////////////////////////
void print_thread()
{
while(1)
{
static int i = 0;
nprintf("no.%d\n", i++);
usleep(100000);
}
}
int main()
{
ninit();
fflush(stdin);
output_win = subwin(win, row - 1, col, 0, 0);
scrollok(output_win, true);
input_win = subwin(win, 1, col, row - 1, 0);
std::thread pthr(print_thread);
std::thread nthr(nmonitor);
string cmd;
while(1)
{
cmd = nget();
if(cmd == "quit")
break;
else
nprintf("[info] You input: %s\n", cmd.c_str());
}
getch();
endwin();
}
环境配置和构建
对于 Mac OSX:
brew install ncurses
对于 Ubuntu:
sudo apt-get install libcurses5-dev
构建:
g++ f04.cpp - f04 -lcurses # I try for 4 times so name it f04
一些错误
其实它有一些bug,在这里我发现了:
- 当你输入退格时,它不会删除一个字符而是显示一个特殊的字符;
- 输入enter后,output_win有时会显示一些奇怪的字词。
我是初学者,可能需要帮助。
(也许我很快就会解决它们。)
愿它确实可以帮助别人。