微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ncurse库在for循环中向右打印字符的问题

如何解决ncurse库在for循环中向右打印字符的问题

我使用 Xshell 连接到远程主机并编写 ncurse 程序。但是发现不能向右循环打印字符。

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

结果: Only the first character is printed.

为了打印出来,我不得不添加刷新代码

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

我认为BIG问题导致Box功能不可用,因为一个Box的两条Horizo​​ntal线没有完成,它也只有第一个'-'。

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

结果: Notice the two horizontal lines up and down

我无法弄清楚这个问题。

2021.3.11
我已经确定了问题所在。问题出在 Xshell 上。我通过阿里云服务器官网连接我的主机,程序没有问题。但我还是不知道如何设置我的 xshell。

解决方法

使用以下代码(保存到 test.c 并使用 gcc -o test test.c -lncurses 编译)我可以绘制边框,将文本放入其中,并将文本放入主窗口。

#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);
    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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。