• Advertisement


This topic is now archived and is closed to further replies.

C Question

This topic is 5156 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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() {
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &tempInfo);
return tempInfo.dwCursorPosition;

[edited by - BiTwhise on January 13, 2004 2:20:02 PM]

Share this post

Link to post
Share on other sites
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[i] = ''\0'';
strcat(buf, p);
printf("%s\n", p);

I didn''t test this code, but something like this should work

Share this post

Link to post
Share on other sites

  • Advertisement