title: C - printf and scanf buffer
body: <p>I'm sorry about the generic title, but i didn't find anything better.
  And I'm sorry if the question is stupid but I'm a novice and I could not find anything of use to me.    </p>
  
  <p>I have written this code to solve a simple problem: you have a sequence of positive integers terminated by a negative: for every integer you have to print a corresponding amount of <code>*</code> characters and go to a new line.</p>
  
  <p>The code DOES WORK but I can't really understand WHY.</p>
  
  <pre><code>int main()
  {
      int d=0,i;
      while (d&gt;=0){
          scanf("%d",&amp;d);
          for (i=0;i&lt;d;i++)
          {
              printf("*");
          }
          printf("\n");
      }
      return 0;
  }
  </code></pre>
  
  <p>I did a bit of research and I understand that terminal gives the integer sequence to <code>scanf</code> only when I press return.
  I thought it would work this way:   </p>
  
  <ul>
  <li><code>scanf</code> gets the integer sequence it registers the first one while the others are discarded </li>
  <li>prints the amount of <code>*</code>s corresponding to the  first integer</li>
  </ul>
  
  <p>Instead it seems that <code>scanf</code> reads the first integer, then printf sends it to a buffer then the cycle restarts and <code>scanf</code> gets the second integer and so on.
  When the last positive integer is reached <code>printf</code> flushes the buffer.</p>
  
  <p>Am I wrong? And if not, why does it work this way?</p>