Search code examples
cprintingsleepcurses

Curses Functions in C,print out default message and blinking


Display a blinking message in the center of the screen. If the user supplies a message on the command line, your program should display that message, otherwise the default message is displayed. Use the sleep function to pause the program between printing the message and then erasing it. Here is what i did so far,i only can print and blinking the message is what i input, but i can not print the default message.

#include <ncurses.h>            
#include <string.h> 
 
int main()
{
    char mesg[50]="";       
    int row,col;                         
    initscr();  
    scanf("%s",&mesg);
    getmaxyx(stdscr,row,col);
    for(int i=0;i<8;i++){
        if(i%2==1)
            standout();    
        mvprintw(row/2,col/2,"%s",mesg);
        sleep(1);
        if(i%2!=1)
            standend();
        mvprintw(row/2,col/2,"%s",mesg);                                
        refresh();
    }
    getch();
    endwin();

    return 0;
}

thanks for you guys help!


Solution

  • Define main as int main(int argc, char *argv[]) (or char **argv) to access command line parameters. Assuming argc >= 1, the program name will be in argv[0], and if argc > 1, the command line parameter strings will be in argv[1] through to argv[argc - 1]. argv[argc] will be a null pointer.

    #include <ncurses.h>
    #include <string.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[])
    {
        const char *mesg;
        int row,col;
        int startcol;
    
        if (argc > 1) {
            mesg = argv[1];
        } else {
            mesg = "Default message";
        }
        initscr();
        getmaxyx(stdscr,row,col);
        if (strlen(mesg) > col) {
            startcol = 0;
        } else {
            startcol = (col - strlen(mesg)) / 2;
        }
        for(int i=0;i<8;i++){
            if(i%2==1)
                standout();    
            mvprintw(row/2,startcol,"%s",mesg);
            sleep(1);
            if(i%2!=1)
                standend();
            mvprintw(row/2,startcol,"%s",mesg);                                
            refresh();
        }
        getch();
        endwin();
    }