title: C - Find longest word in a sentence
body: <p>Hi I have this program that reads a text file line by line and it's supposed to output the longest word in each sentence. Although it works to a degree, it's overwriting the biggest word with an equally big word which is something I am not sure how to fix. What do I need to think about when editing this program? Thanks</p>
  
  <pre><code>//Program Written and Designed by R.Sharpe
      #include &lt;stdio.h&gt;
      #include &lt;stdlib.h&gt;
      #include &lt;string.h&gt;
      #include "memwatch.h"
  
  int main(int argc, char** argv)
  {
      FILE* file;
      file = fopen(argv[1], "r");
      char* sentence = (char*)malloc(100*sizeof(char));
      while(fgets(sentence, 100, file) != NULL)
      {
          char* word;
          int maxLength = 0;
          char* maxWord;
          maxWord = (char*)calloc(40, sizeof(char));
          word = (char*)calloc(40, sizeof(char));
          word = strtok(sentence, " ");
          while(word != NULL)
          {
              //printf("%s\n", word);
              if(strlen(word) &gt; maxLength)
              {
                  maxLength = strlen(word);
                  strcpy(maxWord, word);
              }
              word = strtok(NULL, " ");
          }
          printf("%s\n", maxWord);
          maxLength = 0; //reset for next sentence;
      }
  
      return 0; 
  }
  </code></pre>
  
  <p>My textfile that the program is accepting contains this</p>
  
  <pre><code>some line with text 
  another line of words 
  Jimmy John took the a apple and something reallyreallylongword it was nonsense
  </code></pre>
  
  <p>and my output is this</p>
  
  <pre><code>text
  
  another
  reallyreallylongword
  </code></pre>
  
  <p>but I would like the output to be</p>
  
  <pre><code>some
  another
  reallyreallylongword
  </code></pre>
  
  <p><strong>EDIT: If anyone plans on using this code, remember when you fix the newline character issue don't forget about the null terminator. This is fixed by setting
  sentence[strlen(sentence)-1] = 0 which in effect gets rid of newline character and replaces it with null terminating.</strong></p>