Hi All,
I've just started to learn C from "The C Programming Language" (Kernighan). One of the exercises asks you to write function that folds a line of text into newlines after x number of characters without splitting a word.
This is my attempt so far:
// fold: folds the line into newlines
void fold(char s[], int l) {
int i, j, foldHere;
i = j = 0;
foldHere = FOLDLENGTH;
while (i < l) {
if (i != ' ') {
j = i;
while (j != ' ' && j < l) {
++j;
if (j == foldHere)
putchar('\n');
}
while (i < j) {
putchar(s[i]);
++i;
}
} else {
if (i == foldHere)
putchar('\n');
else
putchar(s[i]);
++i;
}
}
}
s[] is holding the string.
l is the size of s[].
I've defined (#define) FOLDLENGTH to be 10.
I've been testing with the string "This is malfunctioning".
The output I get is: a newline, the string.
Instead of having the newline placed in the sting before "malfunctioning" is output.
I feel that the problem is perhaps my misunderstanding of putchar().
Where am I going wrong?
Thank in advance for any help offered.