C Programming: A Modern Approach - Chapter 15 Exercise 5



Hi,

Does anybody have a solution or a hint for Exercise 5 of Chapter 15 of
K.N. King's book C Programming: A Modern Approach? I spent all of
yesterday evening staring at it and drooling. The author sure does have a
knack for making me feel like a dumbass, or maybe it's just that I am.

The following code pads out sentences with extra spaces between words so
that each line takes up the same amount of space on screen. As is, the
code will favour the end of the line when distributing the extra spaces.
The task is to modify it so that it alternates between distribution of the
extra spaces favouring the end of the line and the beginning of the line.

void write_line(void)
{
int extra_spaces, spaces_to_insert, i, j;

extra_spaces = MAX_LINE_LEN - line_len;
for (i = 0; i < line_len; i++) {
if (line[i] != ' ')
putchar(line[i]);
else {
spaces_to_insert = extra_spaces / (num_words - 1);
for (j = 1; j <= spaces_to_insert + 1; j++)
putchar(' ');
extra_spaces -= spaces_to_insert;
num_words--;
}
}
putchar('\n');
}

I cannot for the life of me figure out a solution beyond parsing the
sentence first and adding the number of spaces to an array to be used when
printing the sentence to screen, but this feels like an awful kludge. The
closest I've come to a decent solution is to add extra_spaces % (num_words
- 1) to spaces_to_insert but this results in the extra spaces not being
distributed evenly.

Thanks.

.



Relevant Pages