简体   繁体   中英

How can I align text to the center in terminal?

I want to have my text horizontally aligned to the center in the terminal. How can I do this in C?

To expand on @eyalm's answer: if you got the COLUMNS var, you can center strings like this:

int columns = strtol(getenv("COLUMNS"), NULL, 10);
int fwidth = strlen(s) + (columns - strlen(s)) / 2;
printf("%*s\n", fwidth, s);

如果您正在使用bash,请使用COLUMNS环境变量来获取宽度并COLUMNS

This is a very old post, but I thought I would add this.

With a bit of maths, you are able to do the following:

char *myText = "Hello, world!";
int x, y;
getmaxyx(stdscr, y, x);
mvaddstr(stdscr, y / 2, (x / 2) - (strlen(mytext) / 2)), myText);

The way it works:

You get half of the screens width, and subtract it by half of the length of the text. This will center your text to the screen. (It works for any window size!)

If your to lazy like me to write all that code here is a easy solution.

 Console.WriteLine("                  Hello World");
 Console.ReadLine();

Add more space if needed until its center LOL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM