/* * WC -- program to count characters, words, and lines in the input * * Usage: wc * * Inputs: text to count characters, words, lines * Output: character, word, line counts * Exit Code: EXIT_SUCCESS (0) because all goes well * * Approach: * counting characters: increment char counter after each char is read * counting lines: increment line counter after each '\n' is read * counting word: initially, start not in word; when you read a non- * space, enter word and increment word counter; when you read a * space, leave word (so you are not in word); repeat until enf * of file read * * Matt Bishop, ECS 36A, Fall 2019 * October 12, 2019: modified from a program written for ECS 30 */ #include #include #define IN_WORD 1 /* currently inside a word */ #define NOTIN_WORD 0 /* currently not in a word */ /* * count the number of lines, words, and chars in the input * a word is a maximal sequence of nonspace characters, so * the quote "+++ --- hi bye 879+3" has 5 words ("+++", "---", * "hi", "bye", and "879+3") */ int main(void) { int c; /* input char */ int nl; /* line count */ int nw; /* word count */ int nc; /* char count */ int state; /* in or not in a word? */ /* * initialize */ nl = nw = nc = 0; state = NOTIN_WORD; /* * handle input a char at a time */ while((c = getchar()) != EOF){ /* got another character */ nc++; /* is it a newline? */ if (c == '\n') nl++; /* is it a word separator? */ if (c == ' ' || c == '\t' || c == '\n') /* YES -- change state */ state = NOTIN_WORD; else if (state == NOTIN_WORD){ /* NO -- we're now in a word; update */ /* the counter and state if need be */ state = IN_WORD; nw++; } } /* * announce the results and quit */ printf("%6d\t%6d\t%6d\n", nl, nw, nc); exit(EXIT_SUCCESS); }