"The C Programming Language", 2nd edition, Kernighan and Ritchie

Answer to Exercise 1-12, page 21

Solution by Richard Heathfield

Write a program that prints its input one word per line.


#include <stdio.h>
int main(void)
{
  int c;
  int inspace;

  inspace = 0;
  while((c = getchar()) != EOF)
  {
    if(c == ' ' || c == '\t' || c == '\n')
    {
      if(inspace == 0)
      {
        inspace = 1;
        putchar('\n');
      }
      /* else, don't print anything */
    }
    else
    {
      inspace = 0;
      putchar(c);
    }
  }
  return 0;
}


Back to index





You are visitor number - call again soon!