Centering text is one of those basic things many programmer’s have to deal with. Yet once you write the function, you might forget about something I called bounds checking. After all, who would ever pass a string to a centering function where that string would be wider than the field in which it’s centered?
Let me put that another way.
When you write a centering function, as you may have done for last month’s Exercise, you supply the function with the string to be centered plus a width value:
center(char *text,int width)
You could, if you want to live dangerously, omit the width value. Many programs would just assume that the width is the current text screen’s width. That’s typically 80 characters. That’s simple and easy and it probably would work just fine, but it’s not good programming practice.
If you include the width value, then the function you devise to center text might look like my solution from last month:
void center(char *text,int width) { int s,length,indent; length = strlen(text); /* I included string.h above */ indent = (width-length)/2; /* determine the setback */ for(s=0;s<indent;s++) /* pad `s` spaces */ putchar(' '); puts(text); /* display the text */ }
Don’t pat yourself on the back just yet.
As a programmer you need to think in variables and try to reason out possibilities that may not be apparent. That’s a tough job because normally you’re just trying to provide a solution. Yet once that task is done, you need to think about breaking your code as well. Consider all possibilities. For example, what happens when the text
string is longer than the given width
?
No, the program won’t crash. That’s good. The code won’t overflow and stomp all over memory. Still, the output won’t be what’s intended; it will look ugly.
To prevent the centered text from overflowing you need to employ bounds checking: Write code that determines whether the string text
is longer than the width
. If so, the function truncates the string. Brutal, yes, but such action is often necessary to control output.
How do you truncate the string? That task is up to you. You can lop off the end, center the string and then lop off the left and right ends, or do whatever. You could even concoct a function that slices the string at a white space character. However you do it, the task is this month’s Exercise: Fix the center() function so that it truncates a string to a given width.
Here’s your skeleton:
#include#include #define W 64 void center(char *,int); int main() { center("If you don't know where you are going, you might wind up somewhere else.",W); center("Baseball is ninety percent mental and the other half is physical",W); center("In theory there is no difference between theory and practice. In practice there is",W); return(0); } void center(char *text,int width) { }
Your job is to complete the code by writing the center() function, which appropriate truncating action.
Please avoid looking at my solutions before you have tried the Exercise on your own.