0

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.

user31782
  • 7,087
  • 14
  • 68
  • 143

3 Answers3

2

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.

Zéychin
  • 4,135
  • 2
  • 28
  • 27
1

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.

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
1

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.

Philipp Murry
  • 1,660
  • 9
  • 13
  • My book doesn't mention that I have to press Enter for getchar to terminate. :( – user31782 Dec 04 '14 at 16:06
  • Because it is a very basic concept that you have to press enter to send input to your program. – Philipp Murry Dec 04 '14 at 16:41
  • Your terminal is usually running in 'buffered' and 'local echo' mode. You can change this settings, but how to do so depends on the OS you're using. On DOS/Windows AFAIR you can simply use `getch()` instead of `getchar()`. On Unixes you can either modify termina settings via the `stty` command, or use `curses` or `ncurses` library instead of just using `stdio` `getchar()` that doesn't really know or care what device it is reading from ... – Hartmut Holzgraefe Dec 07 '14 at 14:29