/* ** $Id: wc.c 730 2008-02-08 23:45:00Z phf $ ** ** A *very* simple clone of wc; check out "man wc" to see ** how much more the "real thing" does. ** ** In lecture we did a version that avoided maintaining ** word/whitespace state explicitly by keeping the last ** two characters around; a decent alternative. :-) */ #include #include #include #include int main() { // Counters: characters, words, and lines so far! int chars = 0; int words = 0; int lines = 0; // Flag: Are we currently reading whitespace? bool white = true; int c; while ( (c = getchar()) != EOF ) { // every character counts chars += 1; // every newline counts as well if ( c == '\n' ) { lines += 1; } // on transition from non-white to white we count a word if ( isspace( c ) ) { if ( !white ) { white = true; words += 1; } } else { // !isspace( c ) white = false; } } // If the file ended while we were inside a word, // we need to count one more (end of file is an // "implicit" transition out of a word). Thanks // to Rinat Zakirov who caught this in lecture! if ( !white ) { words += 1; } // The format here doesn't quite match that of the // real wc tool. printf( "\t%d\t%d\t%d\n", lines, words, chars ); return EXIT_SUCCESS; }