I had a general question earlier and got great responses, but now (even though it's the same exercise) I have a more specific question and thought it deserved it's own Q&A page.
Here's my program (not completed, but it compiles and runs ok) :
#include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
// #define MAXWORDLENGTH 10
// print a histogram of the length of words in input. horizontal bar version
int main(void)
{
int c, state, length;
int one, two, three, more;
length = 0;
one = two = three = more = 0;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n')
state = OUT;
else state = IN;
if (state == IN) {
++length;
while ((c = getchar()) != EOF && state != OUT) { // get next character in word
if (c != ' ' && c != '\t' && c != '\n') // if character is not whitespace...
++length; // ...add one to length
else state = OUT; // otherwise word is over
}
if (length != 0) {
if (length == 1)
++one;
if (length == 2)
++two;
if (length == 3)
++three;
if (length > 3)
++more;
}
length = 0;
}
}
printf("----------------------------------------------------------------\n");
// print histogram
printf("ONE: %d\tTWO: %d\tTHREE: %d\tMORE: %d\n", one, two, three, more); // just making sure program collects data right, which it isn't...
printf("----------------------------------------------------------------\n");
return 0;
}
This should be self-explanatory with the comments. I'm using integers for the moment (will switch to an array) and only printing the tallies to make sure it's collecting data right.
Here's the actual program being compiled, run, and tested...
[matt@localhost 1.6]$ cc -Wall e-1-13.c
[matt@localhost 1.6]$ ./a.out
1 22 333 4444 55555
----------------------------------------------------------------
ONE: 2 TWO: 1 THREE: 1 MORE: 1
----------------------------------------------------------------
[matt@localhost 1.6]$ ./a.out
1 1 1 1 1 1
----------------------------------------------------------------
ONE: 3 TWO: 0 THREE: 0 MORE: 0
----------------------------------------------------------------
[matt@localhost 1.6]$ ./a.out
22 22 22 22 22
----------------------------------------------------------------
ONE: 4 TWO: 1 THREE: 0 MORE: 0
----------------------------------------------------------------
[matt@localhost 1.6]$
... as you can see it's not. Sometimes the tally is correct, sometimes it's missing some, sometimes it's got too many. Any idea why?