The C Programming Language

Chapter 1 - A Tutorial Introduction 12

mmresult 2009. 3. 25. 17:26


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;
}