Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

centering output

Status
Not open for further replies.

bells

MIS
Oct 5, 2001
51
CA

I am writing a console C code
How do u center your output to the output screen
thanks


 
Well, is this under Linux, Unix, or DOS, or something completely different?
 
Well, if you want a generic answer this is it:
Firt you must know the number of characters wide your display is. Then you must know the length of the string you wish to center on a line. From this, the basic algorithm is to emit the number of spaces which is HALF the difference between the line length and the string length. Example:

display is 80 chars wide
String is "This is a test" which is 14 characters.

Put out (80-14)/2 spaces, then the string, which is 33 spaces for this example line.

For an odd number, some wish to add an extra space and others wish to leave off the extra space. If you do integer arithmetic you will automatically drop the extra space for these cases. You can add extra code if you wish it to be the other way.

If your system supports it, you may issue a cursor positioning command instead of spaces, but the results are the same.

Also, if you are using a system that supports proportional fonts, then you must do the same thing except instead of counting characters you must measure the string width and know the screen width in pixels (or whatever unit your system uses). The same formula works but just use your unit of meaurement for screen width and string width instead. Then, instead of issuing spaces, you must use some sort of positioning that can get you positioned by pixel (or whatever unit of measurement you are using). This would be the case if you are coding, for example, in a window of a GUI instead of a text-mode terminal.

Unless you are really stuck, I will leave the coding up to you.
B-)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top