C Question

Started by
1 comment, last by turtlemancanada 20 years, 3 months ago
How do you display text in the center of the screen using printf?
Advertisement
you could:
use strlen() to obtain the length of the string. taken you know the width of the screen (in characters. usually 85 I think), you can calculate the number of whitespaces before the text to center it on screen.

you could then, either add whitespaces to your string (or a new string) and print them, or
depending on what platform you're developing on, set the position of the text manually.
in good old c/c++ you had gotoXY(), but in for example Visual C++ this is removed..
In windows, everything is a window .. so you'll have to use some windows function to set the position.
Here are some wrapper functions I wrote way back:
void setXY( COORD coords) {	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coords);}COORD getXY() {	CONSOLE_SCREEN_BUFFER_INFO tempInfo;	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &tempInfo);	return tempInfo.dwCursorPosition;}


[edited by - BiTwhise on January 13, 2004 2:20:02 PM]
assuming that the string you are printing is less than the width of the screen:

#define SCREEN_WIDTH 80 /* change if not correct */

f(char *p)
{
char buf[SCREEN_WIDTH+1] = "\0";
int i, n, half_n, width_half;
n = strlen(p);
half_n = n / 2;
width_half = SCREEN_WIDTH / 2;
for (i = 0; i < width_half - half_n; i++)
buf = '' '';
buf = ''\0'';<br>strcat(buf, p);<br>printf("%s\n", p);<br>}<br><br>I didn''t test this code, but something like this should work </i>

http://www.mildspring.com - developing android games

This topic is closed to new replies.

Advertisement