I want to have my text horizontally aligned to the center in the terminal. How can I do this in C?
Asked
Active
Viewed 6,422 times
5
-
1[What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Some programmer dude Feb 17 '13 at 14:07
-
1You'll probably want ncurses or similar. – cnicutar Feb 17 '13 at 14:11
-
This might help: http://stackoverflow.com/questions/1022957/getting-terminal-width-in-c – John Zwinck Feb 17 '13 at 14:11
-
How about using `printf("%*s\n", strlen(s) + (80 - strlen(s)) / 2, s);` or the ncurses library? – Feb 17 '13 at 14:11
-
Check your math, @H2CO3. I think you want 40 - strlen(s)/2, which would be just (80 - strlen(s))/2. – Adam Liss Feb 17 '13 at 14:16
-
@AdamLiss Check your local copy of the documentation of `printf()` :) It takes field width, not initial padding, and anyway **I just tried it...** – Feb 17 '13 at 14:18
-
Ah, of course. Sorry for the silly error! Why not repeat your comment as an answer (and use COLUMNS as well), so we can upvote it? :-) – Adam Liss Feb 17 '13 at 14:21
4 Answers
5
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);
2
If you are working with bash, use COLUMNS
environment variable to get the width and calculate the center.

eyalm
- 3,366
- 19
- 21
0
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!)

Nebula Developments
- 11
- 1
-3
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

TheBoringGuy
- 155
- 6
- 14