Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.08 on page 20

Write a program to count blanks, tabs, and newlines.



Solution by Richard Heathfield

#include <stdio.h>

int main(void)
{
  int blanks, tabs, newlines;
  int c;
  int done = 0;
  int lastchar = 0;

  blanks = 0;
  tabs = 0;
  newlines = 0;

  while(done == 0)
  {
    c = getchar();

    if(c == ' ')
      ++blanks;

    if(c == '\t')
      ++tabs;

    if(c == '\n')
      ++newlines;

    if(c == EOF)
    {
      if(lastchar != '\n')
      {
        ++newlines; /* this is a bit of a semantic stretch, but it copes
                     * with implementations where a text file might not
                     * end with a newline. Thanks to Jim Stad for pointing
                     * this out.
                     */
      }
      done = 1;
    }
    lastchar = c;
  }

  printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);
  return 0;
}

Solution by Thomas Blakely

I am of the opinion K&R wrote their exercises using only what has been taught thus far. Quite concise, really.

#include <stdio.h>

/* Write a program to count blanks, tabs, and newlines
 * i.e. ' ', \t, \n */

main()
{
        int c;                  // c = character
        int ns, nt, nl;         // ns = space; nt = tab; nl = lines
        ns = nt = nl = 0;       // start at zero mark

        while ( (c = getchar() ) != EOF )
        {
                if ( c == ' '  )
                        ++ns;
                if ( c == '\t' )
                        ++nt;
                if ( c == '\n' )
                        ++nl;
        }

        printf("------------------\n");
        printf("Total spaces:\t%d\n", ns);
        printf("Total tabs:\t%d\n", nt);
        printf("Total lines:\t%d\n", nl);

}

Solution by Sachin Mudaliyar

Os: linux
Compiler used : cc

// by user S4ch1n
#include<stdio.h>
void main()  {
	int c, nb, nt, nl; 
	nb = nt = nl = 0;
	while ((c = getchar()) != EOF)  {
		if (c == 32)  { // ascii value for " "
			nb++;
		}
		if (c == 9)  { // ascii value for "\t"
			nt++;
		}
		if (c == 10)  { // ascii value for "\n"
			nl++;
		}
	}
	printf("%d %d %d\n", nb, nt, nl);
}

Personal tools