title: Understanding getchar() in the character counting program in C
body: <p>This is a follow-up question of my <a href="https://stackoverflow.com/q/27336297/3429430">previous</a> question. There is already a similar question asked(<a href="https://stackoverflow.com/q/27183865/3429430">question</a>). But I don't get what I want to know from that answer.</p>
  
  <p>From the previous question I come to know that if I type a lot of characters, then they are not made available to getchar(), until I press Enter. So at the very point when I press Enter, all the characters will be made available to getchar()s. Now consider the following program for character counting:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  main()
  {
    long nc;
    nc=0;
    while(getchar()!=EOF)
    ++nc;
    printf("    Number of chars are %ld ",nc);
  }
  </code></pre>
  
  <p>If I input characters from the command line in the following sequence: {1,2,3,^Z,4,5,Enter}, then in the next line {^Z,Enter}. The output that I expect is: <code>Number of chars are 6</code>. But the output that I am getting is <code>Number of chars are 4</code>.</p>
  
  <p>This <a href="https://stackoverflow.com/a/27184020/3429430">answer</a> explains that when we input<code>1,2,3,^Z</code>, then <code>^Z</code> acts like <code>Enter</code> and 1,2,3 are sent to getchar()s. The while loop of the above written code runs three times. <code>^Z</code> is not given to getchar(), so the program doesn't terminate yet. My input was {1,2,3,^Z,4,5,Enter}. After ^Z I had pressed 4,5 and then Enter. Now when I press Enter the characters 4,5 and Enter, should be given to getchar()s and the while loop should execute three times more. Then in the last line I input {^Z,Enter}, since there is no text behind ^Z, it is consider as a character and when I press Enter, this ^Z is given as the input to getchar() and the while loop terminates. In all this, the while loop has executed 6 times, so the variable <code>nc</code> should become <code>6</code>.</p>
  
  <blockquote>
    <ul>
    <li>Why am I getting <code>4</code> as the value of <code>nc</code>, rather than <code>6</code>.</li>
    </ul>
  </blockquote>