1

Here is my code:

#include <stdio.h>

int main()
{
        char a = getchar();
        printf("char: %c", a);
}

I'm compiling this with gcc.

When running, the program waits for input even after one character is entered on console. Shouldn't it immediately exit and print the character? I'm running this on Ubuntu for Windows, if that can make any difference.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
upInCloud
  • 979
  • 2
  • 10
  • 29

2 Answers2

7

stdin is your default input stream. The default buffering mode of stdin is line buffered. So it waits for the \n to be entered. Then only there is something to read from the input stream and then getchar gets the input and works with it.

user2736738
  • 30,591
  • 5
  • 42
  • 56
4

The operating system often buffers console input until a new line is entered, such that your program will not even receive the single character before. Probably nothing you can do about that.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58