Search code examples
cprintfgetchar

Printf waiting for enter


int kr=0;
int ss =0;
while ((kr=getchar()) != EOF){
      if(kr != '\n')
      {
        ss++;
      }

      printf("%d\n",ss);
}

With this code , printf is waiting until i press enter then printing all the sequential ss values at the same time like in this

enter image description here

. Can somebody explain this behavior ?


Solution

  • printf is not waiting it is getchar instead. getchar uses a buffer behind the scene. When that buffer is empty, getchar will read 1 line from stdin and then return the first caracter. If it is not empty, it will return the next caracter from the buffer immediatly.

    That means that the getchar will wait the first time you call it. And thus your printf is never executed until you press enter