Getchar () gives the result 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 he does is pretty weird. It displays whatever I click. It never ends until I press Enter.

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

  • Why does it print every character I enter?

Edit:

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

   #include <stdio.h>  

   main()  

   {  

    getchar();  

   printf("Done");  


  }  

      

The program should print Done after reading one character.

0


source to share


3 answers


Your program will not complete until finished getchar()

. getchar()

is not filled until the input buffer is full. The input buffer is not filled until you press Enter.



The character you see is the character you are printing. This is the default terminal based behavior, not controlled by your program.

+2


source


You press a key, so your console shows you the same symbol. This was expected behavior. getch()

will also return the ascii value of the character that is printed to the screen.



+1


source


Which getchar

is basically what reading from stdin does. This is a file with file descriptor 0, and it usually refers to the terminal you enter (unless you change it to some file via <

, for example cat < sample.txt

). As with any file, you can call read

0 in file - in the case of a terminal, read

will respond as soon as you type something in the terminal and hit enter . If you don't, the call read

to stdin just waits until it receives something to read. This is why your program is waiting: it calls read

on stdin (file 0), and since stdin is a terminal, it read

will only return after you hit enter. I hope you have some understanding about file handling, otherwise this answer may confuse you a little.

+1


source







All Articles