I'm trying to write a program to that acts as a marquee that uses the curses.h library
to create a side-scrolling display.
What should happen is that my message "Hello" should appear to scroll from the right side of the terminal to the left, character by character.
"hello" should appear to scroll across the terminal like so:
| H| // fist frame of animation
| He| //2nd
| Hel| //3rd
...
| Hello | // some time in the middle of animation
|Hello | // finished.
Instead of appearing to scroll across the terminal my program simply outputs the "Hello" message on the left side of the terminal as if it is finished.
I thought that printing the appropriate number of spaces then the appropriate number of characters of the string each frame would work.
What am I doing wrong?
Below is my code so far:
#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
}
}
The first problem is that you call
getmaxyx()
beforeinitscr()
. In this situation,stdscr
has not been initialized, so the values returned bygetmaxyx()
are meaningless. (I get -1 for each value, aka ERR.)That fixed, the program basically works, but prints junk after the "Hello" string. You can solve that by changing the for loop test,
text_length || i<max_x
, totext_length && i<max_x
, although the result is still probably not quite what you want. But I'll leave it to you to figure that one out.Finally, as a stylistic matter, I'd suggest using curses' own
napms()
function instead ofusleep()
(i.e.,napms(50)
instead ofusleep(50000)
). But if you do stick withusleep()
, you should add#include <unistd.h>
at the top.