user31782
user31782

Reputation: 7589

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.

Upvotes: 0

Views: 769

Answers (3)

Z&#233;ychin
Z&#233;ychin

Reputation: 4205

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.

Upvotes: 2

Philipp Murry
Philipp Murry

Reputation: 1682

What getchar basically does is reading from stdin. This is a file with file descriptor 0 and it usually refers to the terminal that you type in (unless you change it to some file via <, e.g. cat < sample.txt). Like with any file, you can call read on file 0 - in case of the terminal, read will respond as soon as you type something into the terminal and hit enter. Unless you do so, the call to read on stdin just waits until it gets something to read. This is why your program is waiting: It calls read on stdin (file 0), and since stdin is the terminal, read will only return when you hit enter. I hope you have some understanding on file handling, otherwise this answer might confuse you a bit.

Upvotes: 1

Pranit Kothari
Pranit Kothari

Reputation: 9841

You are pressing key, so your console is showing same character to you. It's expected behaviour. getch() will also return ascii value of character that is being printed on screen.

Upvotes: 1

Related Questions