Exercise 1.12 - Print the input one word per line

Question

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

Solution

/**
 *
 * Exercise 1.11 - Write a program that prints its input one word per line.
 *
 * */

#include <stdio.h>
#define IN 1
#define OUT 0

/* This program counts the number of lines, characters and words */
int main (int argc, char *argv[]) {
  int c,state;
  state = IN;
  while((c=getchar()) != EOF) {
    if(c==' ' || c == '\t')
      state=OUT;
    else if (state == OUT) {
      state=IN;
      putchar('\n');
      putchar(c);

    }
    else
      putchar(c);
  }
}

Explanation

In this program, we read the one character at a time and check if the character is a space ‘ ‘, we print newline character, ‘n’ thus going to next line in the output, otherwise we simply print the character c.