利用curses库编程开始

本文介绍了curses库的常用函数,并通过四个逐步进阶的小例子,展示了如何在终端上进行交互式编程。从基本的窗口操作到更复杂的界面控制,帮助读者掌握curses库的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

curses库常用函数:

注意编译时要用这样的格式:gcc xxx.c -l curses -o xxx

第一个小例子:

include <stdio.h>
#include <curses.h>

int main()
{
    initscr();

    clear();
    move(10,20);
    addstr("Hello, world");
    move(LINES-1, 0); 
    refresh();
    getch();
    endwin();
    return 0;
}
运行效果如下:


第二个小例子:

#include <stdio.h>
#include <curses.h>

int main()
{
    int i;

    initscr();
    clear();
    for (i = 0; i < LINES; i++)
    {   
        move(i, i+1);
        if (i%2 == 1)
            standout();     //反白显示
        addstr("Hello, world");
        if (i%2 == 1)
            standend();     //关闭反白显示
    }   
    refresh();
    getch();
    endwin();
    return 0;
}
运行效果:

第三个小例子:

#include <stdio.h>
#include <curses.h>

int main()
{
    int i;

    initscr();
    clear();
    for (i = 0; i < LINES; i++)
    {   
        move(i, i+1);
        if (i%2 == 1)
            standout();
        addstr("Hello, world");
        if (i%2 == 1)
            standend();
        refresh();
        sleep(1);
        move(i, i+1);                   //move back
        addstr("             ");        //erase the line appear before
    }   
    endwin();
    return 0;
}
运行效果:字符串沿着对角线一行一下行的向下移动

第四个小例子:

#include <stdio.h>
#include <curses.h>

#define LEFTEDGE    10  /* 左边界 */
#define RIGHTEDGE   30  /* 右边界 */
#define ROW         10  

int main()
{
    char *message = "Hello";
    char *blank = "     ";
    int dir = 1;
    int pos = LEFTEDGE;

    initscr();
    clear();
    while (1) 
    {   
        move(ROW, pos);
        addstr(message);        /* draw string */
//      move(LINES-1, COLS-1);
        refresh();              /* show string */
        sleep(1);
        move(ROW, pos);         /* move back */
        addstr(blank);          /* erase string */
        pos += dir;             /* advance position */
        if (pos >= RIGHTEDGE)   /* check for bounce */
            dir = -1; 
        if (pos <= LEFTEDGE)
            dir = 1;
    }   
    return 0;
}
运行效果:在(ROW,LEFTEDGE)----(ROW,RIGHTEDGE)间来回移动字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值