Print output one word per line - K&R Exercise 1-12 When writing this code I found myself getting more and more complex. When I got to the solution I trimmed the excess parts I'd thought I needed from before, but didn't actually need. The example of wc.c had some definitions for IN and OUT. Why didn't I need those for writing this example?

If there are any bugs or improvements I can make, let me know.

include &lt;stdio.h&gt;

/* prints its input one word per line */
main()
{
  int c;

  c = 0;
  while ((c = getchar()) != EOF) {
     if (c == ' ')
      putchar('\n');
     else
       putchar(c);
  }
}
include &lt;stdio.h&gt;


You're missing a # there, copy/paste issue?

main()


That's been out of style for a very long time, and is in fact no longer valid according the standard (from C99 and on). Always specify the return type (for main and all other functions).

int main()




int c;

c = 0;


Don't keep uninitialized variables around for any length of time if you can avoid it. A bit trivial here, but nonetheless prefer:

int c = 0;


In this specific case, as Jonathan Leffler pointed out, you're unconditionally initializing c in the very next line, so the initialization is not necessary.

(Starting with C99, you can declare variables as you need them. You don't have to stack them all at the top. So as far as possible, only declare variables at the point where they are needed and initialize them at the same time.)



if (c == ' ')
 putchar('\n');
else
  putchar(c);


Your indentation's out of whack here, the first putchar should be indented one with one more space.



As for "bugs", your program won't print what is usually expected if, summarizing points made in Stat1c_V01D's answer and comments by Jonathan:


The input contains empty lines. You'll output empty lines too. They should be omitted.
The input contains whitespace other than plain spaces and newlines (e.g tabs or form feeds). Your code will not split those out. Look at isspace.
The input contains consecutive whitespace characters. Your program will output consecutive new lines between words.
The output doesn't end with a \n. Your program won't output one either which is "bad form". On a Unix terminal, you'll end up with no newline between the last word output and the new prompt.


That's why extra bookkeeping is needed in the solutions you find for this exercise.