CSM217: C for Computer Scientists

Lecture 2: Exercise 2: Solution

#include <stdio.h>

main() {
 char c; // store the character just read in a char, more efficient than int
 int blanksRead = 0; // this will be 0 is no blanks have been read, 
                     //           != 0 otherwise
 while ((c = getchar()) != EOF) {
  if (c == ' ' && blanksRead == 0) {
   putchar(c);
   blanksRead++;
  } else if (c != ' ') {
   blanksRead = 0;
   putchar(c);
  }
 }
}