Reputation: 970
I am going though the "The C Programming Language" by K & R. I am trying to do the exercise 1-13, to get the histogram of length of words of it input. Following is what I tried. I am not getting the last word length. How do I correct this ?
#define space ' '
#define maxLength 100
#include <stdio.h>
int main() {
int c, result[maxLength], count, i, maxWordLength;
count = maxWordLength = 0;
for (i = 0; i < maxLength; ++i)
result[i] = 0;
while ((c = getchar ()) != '0') {
if (!((c == space) || (c == '\t') || (c == '\n')))
++count;
else {
++result[count];
if (count > maxWordLength)
maxWordLength = count;
count = 0;
}
}
for (i = 1; i <= maxWordLength; ++i)
printf("\n%d\t%d\n", i, result[i]);
return 0;
}
Following is my input
1 12
123 1234 12345
1234560
and the output comes like this, it is not giving last word length
1 1
2 1
3 1
4 1
5 1
I have understood why does it happen. But how do I correct it ?
Upvotes: 2
Views: 366
Reputation: 111219
When you reach the 0
that terminates the input you just exit the loop, without adding the length of the last word to the histogram. A possible fix is adding this after the loop:
...
}
/* Take last word into account */
++result[count];
if (count > maxWordLength)
maxWordLength = count;
This is of course assuming that the 0
character indicates the end of the input and is not part of the data.
Upvotes: 1
Reputation: 539685
while ((c = getchar ()) != '0')
should be
while ((c = getchar ()) != EOF)
otherwise your program stops at the first 0
character, e.g. in 1234560
.
And if the last input line is not terminated by a newline, you have to take that also into account.
EOF
is returned at end-of-file or if a read error occurs.
Upvotes: 3