Search code examples
ciogetchar

getchar() is giving output in C


What should this program do,

#include<stdio.h>
main()
{   
  getchar();
}

I expect it to show a blank screen until I hit any character on the keyboard. But what it does is quite weird. It displays whatever I press. It never terminates until I press Enter.

As far as I know, getchar() should just read one character. It should not output anything.

  • Why is it printing every character that I input?

Edit:

Why doesn't getchar() stop after reading one character, e.g. in this code:

   #include <stdio.h>  

   main()  

   {  

    getchar();  

   printf("Done");  


  }  

The program should print Done after reading one character.


Solution

  • Your program won't terminate until getchar() completes. getchar() does not complete until the input buffer is populated. The input buffer is not populated until you press 'Enter'.

    The character you are seeing is the character you are typing. This is default terminal-driven behavior, not driven by your program.