title: Scanf and loops
body: <p>here a a piece of code that is supposed to loop over and over until the user inputs a number between 0 and 15</p>
  
  <pre><code>        int input;
  
          do
          {
  
                  printf("Enter a number =&gt; ");
                  scanf("%d",&amp;input);
                  printf("\n %d \n",input);
  
          }
          while (!(input&gt;0 &amp;&amp; input &lt;15));
  </code></pre>
  
  <p>However if the user puts in something like "gfggdf" it results in the loop repeating over and over and over and never prompting the user for input again... the console looks like this</p>
  
  <pre><code>Enter a number =&gt;
  0
  Enter a number =&gt;
  0
  Enter a number =&gt;
  0
  Enter a number =&gt;
  0
  Enter a number =&gt;
  0
  Enter a number =&gt;
  0
  (looping indefinitely)
  </code></pre>
  
  <p>After looking through this book, it seems I need to do something like this to prevent this from happening.</p>
  
  <pre><code>int input, error, status;
  char skip_ch;
  
  do
  {
          error = 0;
  
          printf("Enter a number =&gt; ");
          status = scanf("%d",&amp;input);
          printf("\n %d \n",input);
  
          if(status!=1)
          {
                  error=1;
          }
          else if(input &lt; 0 || input &gt;15){
                  error = 1;
          }
  
          do
          {
                  scanf("%c",&amp;skip_ch);
          }while(skip_ch != '\n');
  }
  while (error);
  </code></pre>
  
  <p>I understand needing to check for the scanf status to make sure it was valid input, What I don't understand the the inner do-while loop. I feel like the book never really explained to me why scanf needs to be called several times like that, it's like somehow the scanf buffer got filled up with a bunch of garbage and it's somehow cleaning it out by just looping through it a million times for you.</p>
  
  <p>Could anyone please explain this black magic to me?</p>