我正在尝试编写一个程序,该程序充当使用curses.h library
创建横向滚动显示的选框。
发生的是,我的消息"Hello"应该显示为从终端右侧向左滚动,逐个字符。
"你好"应该看起来像这样在终端上滚动:
| H| // fist frame of animation
| He| //2nd
| Hel| //3rd
...
| Hello | // some time in the middle of animation
|Hello | // finished.
我的程序没有在终端上滚动,而是在终端左侧输出"Hello"消息,就好像它已经完成一样。
我认为打印适当数量的空格,然后每帧打印适当数量的字符串字符即可。
我做错了什么?
以下是我到目前为止的代码:
#include <curses.h>
#include <string.h>
main()
{
char message[] = "Hello";
int max_y, max_x; // max dimensions of terminal window
int text_length;
int i,row=0,col=0,spaces=0;
// Get text length
text_length = strlen(message);
// Get terminal dimensions
getmaxyx(stdscr, max_y, max_x);
// num of spaces needed to print
spaces = max_x -1;
initscr(); // initialize curses
clear(); // clear screen to begin
while(1)
{
clear(); // clear last drawn iteration
move(5,col);
// print spaces as necessary
for(i=0;i<spaces;i++)
{
addch(' ');
}
refresh();
// print appropriate number of characters of the message
for(i=0;i<text_length || i<max_x; i++)
{
addch(message[i]);
}
refresh();
usleep(50000); // wait some time
spaces = spaces-1; //adjust spaces need for next iteration
}
}
第一个问题是你在initscr()
之前调用getmaxyx()
。在这种情况下,stdscr
尚未初始化,因此getmaxyx()
返回的值毫无意义。(我为每个值得到 -1,也就是 ERR。
修复后,程序基本有效,但在"Hello"字符串之后打印垃圾。你可以通过将 for 循环测试text_length || i<max_x
更改为 text_length && i<max_x
来解决这个问题,尽管结果可能仍然不是你想要的。但我会留给你去弄清楚这个问题。
最后,作为一个风格问题,我建议使用curses自己的napms()
函数而不是usleep()
(即napms(50)
而不是usleep(50000)
)。但是如果你坚持usleep()
,你应该在顶部添加#include <unistd.h>
。