5

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

amhed
  • 3,649
  • 2
  • 31
  • 56
FredN
  • 161
  • 1
  • 7

4 Answers4

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!)

-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