title: Read from stdin with fgets, bug if input is greater than size
body: <p>I'm creating a command line application with a prompt. It works fine as long as the input fits inside the buffer, but when the input is larger I get some weird behavior. Below is a simplified minimal example which has the same bug.</p>
  
  <pre><code>int main()
  {
      for (;;) {
          const int size = 8;
          char str[size];
  
          printf("&gt; ");
          fgets(str, size, stdin);
  
          toupper_str(str);
          printf("Result: %s\n", str);
      }
  }
  </code></pre>
  
  <p>It works fine if the input is in smaller than <code>size</code>.</p>
  
  <pre><code>&gt; asdf
  Result: ASDF
  &gt; 
  </code></pre>
  
  <p>When the input is larger, the portion of the input in range is processed, and in the next loop iteration, the rest of the given input is immediately returned from <code>fgets</code>. This leads to that portion of the input also being processed and some weird output.</p>
  
  <pre><code>&gt; asdfghjk
  Result: ASDFGHJ
  &gt; Result: K
  
  &gt; 
  </code></pre>
  
  <p>I can see if the input is larger than or equal to size by comparing the last character to a newline. <code>fgets</code> retains the newline as long as it fits.</p>
  
  <pre><code>fgets(str, size, stdin);
  if (str[strlen(str) - 1] != '\n') {
      fprintf(stderr, "Input too long\n");
  }
  </code></pre>
  
  <p>When this is detected, how do I stop it from reading the rest of the too long input on the next iteration?</p>
  
  <p>I've seen similar questions on here, but none that ask the same question.</p>