AS the title. Any way to do the trick? Let's say I want to print "Hello World" in the center of the screen.
asked Mar 9, 2013 at 15:35 17 1 1 gold badge 1 1 silver badge 4 4 bronze badges Just use jQuery for that. [/meta] – user529758 Commented Mar 9, 2013 at 15:37 @H2CO3: Really? Really? ;) Commented Mar 9, 2013 at 15:38 Not enough jQuery. :P Commented Mar 9, 2013 at 15:38If your environment is linux, you may have a look at ncurses library which provides function for manipulating terminal (get width, height, move cursor to a position, draw windows, colors, etc.).
Commented Mar 9, 2013 at 17:54 Most of them make is so much more complicated. Commented Apr 18, 2014 at 4:41You can use the SetConsoleCursorPosition function. Get the width and height of the console window, then call it.
COORD coord; coord.X = width / 2; coord.Y = height / 2; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
answered Mar 9, 2013 at 15:40
9,075 3 3 gold badges 35 35 silver badges 66 66 bronze badges
This assumes the context of the question is a DOS console. That might be valid, but nothing has been provided to suggest this is the case.
Commented Mar 9, 2013 at 15:42 Just a note, this is Windows specific, will not work on Linux, OSX, etc. Commented Mar 9, 2013 at 15:42 @mah: I'm waiting for a response on that. Commented Mar 9, 2013 at 15:43I am working with Windows. It did work but I don't want everything after the syntax at the center, I just want the first line to be at the center. Thanks though..
Commented Mar 9, 2013 at 16:40You need to know how wide a space you need to centre the string in; you need to know how long the string is. You write an appropriate number of blanks, the string, and a newline.
#include int main(void) < int width = 80; char str[] = "Hello world"; int length = sizeof(str) - 1; // Discount the terminal '\0' int pad = (length >= width) ? 0 : (width - length) / 2; printf("%*.*s%s\n", pad, pad, " ", str); return(0); >
An exhaustive test program (up to width 80):
#include #include int main(void) < int width = 80; char str[81]; for (int i = 1; i = width) ? 0 : (width - length) / 2; printf("%*.*s%s\n", pad, pad, " ", str); > return(0); >