/* * File: * countstuff.c * Authors: * Brian W. Kernighan * Dennis M. Ritchie * Samuel A. Rebelsky * Version: * 1.1 of 31 January 2003 * Summary: * Counts various kinds of input characters taken from standard input. * Currently counts digit characters ('0' ... '9'), white space, and * "everything else". * Citation: * Closely based on an unnamed program on page 22 of K&R. */ /* +---------+-------------------------------------------------------- * | Headers | * +---------+ */ #include #include /* +------+----------------------------------------------------------- * | Main | * +------+ */ main() { int ch; /* Temporary variable for input characters. */ int i; /* Counter variable for loops. */ int nwhite; /* The number of whitespace characters. */ int ndigit[10]; /* The number of each digit character. ndigit[0] * contains the number of '0' characters, ndigit[1] * contains the number of '1' characters, and so * on and so forth. */ int nother; /* The number of "other" characters. */ /* Initialize key variables. */ nwhite = nother = 0; for (i = 0; i < 10; ++i) ndigit[i] = 0; /* Read input and count characters. */ while ((ch = getchar()) != EOF) { /* If it's a digit, increment the approropiate counter. */ if ((ch >= '0') && (ch <= '9')) ++ndigit[ch-'0']; /* If it's a whitespace character (space, newline, tab), * increment the whitespace counter. */ else if ((ch == ' ') || (ch == '\n') || (ch == '\t')) ++nwhite; /* Otherwise, it's something else. */ else ++nother; } /* while */ /* Summarize data. */ printf("digits: "); for (i = 0; i < 10; ++i) printf("'%c'=%d ", '0'+i, ndigit[i]); printf("\n"); printf("white space = %d\n", nwhite); printf("other = %d\n", nother); /* Clean up. */ exit(EXIT_SUCCESS); } /* main */