Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a text in the middle of the screen in C programming?

Tags:

c

I did manage to get to the horizontal line (row) to the center but not vertically. Please help, I am still a noob so if you can explain your code, that would be much appreciated.

Thanks

#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>

int main()
{

    struct winsize w; 
    ioctl(0, TIOCGWINSZ, &w); 

    int columns = w.ws_col; 
    int rows = w.ws_row;


    //printf("Lines :  %d\n", rows);
    //printf("Columns ; %d\n", columns);

    char *string = "Hello World";
    int stringLength = strlen(string) / 2;



    printf("%*s\n", columns / 2 + stringLength, string );
    //getchar();                //Pause program

    return 0;
}
like image 455
chichacail Avatar asked Dec 03 '25 15:12

chichacail


1 Answers

No idea why this was down voted. Seems a perfectly valid question.

You've solved the horizontal. Nice job!

If you are in a UNIX environment (Bash especially) you can query the environment variables $LINES and $COLUMNS to find out what the length and width of the screen is.

like image 96
David Hoelzer Avatar answered Dec 05 '25 08:12

David Hoelzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!