title: Why is scanf() causing infinite loop in this code?
body: <p>I've a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input prompt should return again. On input of &quot;0&quot;, the loop should end and the number of given positive/negative values should be printed to the console. Here's the program:</p>
  <pre><code>#include &lt;stdio.h&gt;
  
  int main()
  {
      int number, p = 0, n = 0;
  
      while (1) {
          printf(&quot;-&gt; &quot;);
          if (scanf(&quot;%d&quot;, &amp;number) == 0) {
              printf(&quot;Err...\n&quot;);
              continue;
          }
          
          if (number &gt; 0) p++;
          else if (number &lt; 0) n++;
          else break; /* 0 given */
      }
  
      printf(&quot;Read %d positive and %d negative numbers\n&quot;, p, n);
      return 0;
  }
  </code></pre>
  <p>My problem is, that on entering some non-number (like &quot;a&quot;), this results in an infinite loop writing &quot;-&gt; Err...&quot; over and over. I guess it's a scanf() issue and I know this function could be replace by a safer one, but this example is for beginners, knowing just about printf/scanf, if-else and loops.</p>
  <p>I've already read the answers to the question<a href="https://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c"><code>scanf()</code> skips every other <code>while</code> loop in C</a> and skimmed through other questions, but nothing really answer this specific problem.</p>