I don't much like my previous answer. I think you're supposed to grab a word at a time and print it with one leading space. So I'll describe the pieces and let you put them together. If you can't get it right then show what you have and we'll go from there.
Initialize a pointer as above (but I needn't cast away the const):
const char *s = sentence;
and set a var to hold the number of characters left to fill on the line: int nleft = width;
.
Skip leading spaces: while (*s && *s == ' ') s++;
Now loop until end of string: while (*s)
. Each time you enter the loop, *s
will be the next non-space char to print. Find the boundary after the word and compute the length. If there's not enough room on the line for it (including a space), print a newline, reset nleft
. Then print a space and the word, decrement nleft
by the number of chars printed (including space). The only catch is if the word is too long to fit on a line, then you'll want to print it piecewise.
After printing, advance s
over spaces so it's on a non-space or end of string. After the loop, check if there's anything on the current line and print a newline if so.
At top of loop:
const char *e = s;
while (*e && *e != ' ')
e++;
int len = e - s;
If len
exceeds width - 1
then set it to width - 1
as that's the longest piece you can print on a line.
The line is empty if nleft == width
. There's insufficient space if len + 1 > nleft
. If there's insufficient space AND the line is non-empty, print a newline and reset nleft
. Then print a space and len
chars starting at s
. Note the use of %*.*s
format in my previous answer.
After printing, bump s
by len
and decrement nleft
by number of chars printed. And now loop to advance s to the next nonspace or end of string. Note that if you had printed part of a too-long word (over width-1
chars) then s
is already at the next non-space to print.
Also note that the condition "s
points to next nonspace to print" at the top of the loop is an "invariant", an important concept in reasoning about loops. If a loop isn't obvious, consider what invariants should be maintained by it and what conditions should hold after it exits.