The problem of printing characters to the right in a for loop with the ncurse library

96 Views Asked by At

I use Xshell to connect to a remote host and write ncurse programs. But it was found that the characters could not be printed in a cycle to the right.

#include <ncurses.h>
int main() {
    initscr();
    for (int i = 0;i < 10; i++){
        addch('o');
    }
    refresh();
    getch();
    endwin();
    return 0;
}

Result: Only the first character is printed.

In order to print it all out, I had to add the refresh code

for (int i = 0; i < 10;i++) {
    addch('o');
    refresh();//print all 'o'
}

I think the BIG problem makes the box function unavailable, because the two Horizontal line of a box are not completed, it only have the first '-' too.

int main() {
    initscr();
    curs_set(0);
    WINDOW *win;
    win = newwin(10, 40, 9, 20);
    box(win, 0, 0);
    refresh();
    wrefresh(win);
    getch();
    endwin();
    return 0;
}

Result: Notice the two horizontal lines up and down

I can't figure out this problem.

2021.3.11
I have I have identified the problem. The problem is with Xshell. I connect my host by Alibaba Cloud Server official website, and the program have no problem. But I still don't konw how to set up my xshell.

1

There are 1 best solutions below

1
On

Using the following code (save to test.c and compile with gcc -o test test.c -lncurses) I can draw a border, put text inside it, and also put text in the main window.

#include <ncurses.h>

// Print the character 'ch' in the window
// 'win', and do this 'repeat' times.
int print_chars(WINDOW *win, char ch, int repeat) {
    if (win == NULL) {
    // Print to main window
        for (int i=0; i<repeat; i++) {
            addch(ch);  
        refresh();
        }
    } else {
    // Print to the named window
        for (int i=0; i<repeat; i++) {
            waddch(win, ch);    
        }
        wrefresh(win);
    }
    return 0;
}

int main(int argc, char **argv) 
{
    WINDOW *border_win, *win;
    
    initscr();
    refresh(); // This seems to be needed; 
               // I don't know why.
    
    // Create a window to show the border
    border_win = newwin(10,40,9,20);
    box(border_win,0,0);
    wrefresh(border_win);
    
    // Create a window inside that, which 
    // we will write in.  Otherwise it 
    // seems we will overwrite the border.
    win = newwin(8,38,10,21);
    print_chars(win, 'a', 10);

    // Write something in the main window
    // as well, just to show it works
    print_chars(NULL, 'o', 10);
    
    getch();
    endwin();
    return 0;
}