
Input Statistics
/*
* Program to count the number of lines, find the length of the longest, and
* determine the { } nesting depth. To count the contents of a particular file
* from unix, type
* count < filename
*
*/
#include <stdio.h>
main()
{
int curly_depth = 0, /* Curly bracket nesting depth. */
curly_max = 0; /* Max depth. */
int numlines = 0; /* Number of lines. */
int inchar; /* Input character. */
int linelength = 0, /* Length of current line. */
maxline = 0; /* Lenght of longest line. */
int out_bal = 0; /* Curly braces do not balance. */
/* Read the input file, one character at a time, until EOF. */
while((inchar = getchar()) != EOF)
{
/* Is the current character a left curly brace? */
if(inchar == '{')
{
/* Increase the nesting depth, and updat the
maximum. */
curly_depth++;
if(curly_depth > curly_max)
curly_max = curly_depth;
}
else
/* Is the current character a right curly brace? */
if(inchar == '}')
{
/* Decrease the nexting depth. If it becomes
negative, record an error. */
curly_depth--;
if(curly_depth < 0) out_bal = 1;
}
/* Is the current character an end-of-line? */
if(inchar == '\n')
{
/* Yes. increment the number of lines. */
numlines++;
/* Update the line length maximum, then reset the
counter for the new line. */
if(linelength > maxline)
maxline = linelength;
linelength = 0;
}
else
/* Update the line length. */
linelength++;
}
/* Print results. */
printf("Input contains %d lines, the longest is %d characters.\n",
numlines, maxline);
if(out_bal || curly_depth) /* Note: Implicit curly_depth != 0 */
printf("The curly braces are not balanced.\n");
else
printf("The curly braces are balanced, nested to depth %d.\n",
curly_max);
}