title: C Program: Need to Read Multiple Lines of Input Until EOF and Count Words and Number of Lines
body: <p>I am new to C and I am having trouble with this program. I'm trying to read text from stdin until EOF and write to standard output the number of words read and the number of lines of input. A word being defined as any string of characters except whitespace. My problems are (1) when the program has to read the last word in a line, it reads an end of line and not a whitespace so it does not add the word, and (2) when the program has to read multiple lines of input. Do I need to do a nested for loop with fgets to read until != "\n"? I am not sure on that one. Here is what I have right now:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  
  
  int main ()
  {
      char previousLetter;
      char line[500];
      int numberOfWords, numberOfLines, length, i;
  
      while (fgets (line, 500, stdin) != NULL)
      {
          length = strlen(line);
          if (length &gt; 0)
          {
              previousLetter = line[0];
          }
          for (i=0; i &lt;= length; i++)
          {
              if(line[i] == ' ' &amp;&amp; previousLetter != ' ')
              {
                  numberOfWords++;
              }
          previousLetter = line[i];
          }
         numberOfLines++;
     }
     printf ("\n");
     printf ("%d", numberOfWords);
     printf (" %d", (numberOfWords / numberOfLines));
  }
  </code></pre>