3

CODE:-

char ch,ch1;
ch=getchar();
ch1=getch();
printf("%c\n%c",ch,ch1);

When I enter a character during ch=getchar(), I have to press enter key, which remains in input buffer.
That enter key is not read by the ch1=getch(). Why ch1=getch() is not reading the remaining enter key?

contradictory to this fact
CODE 2:-

char ch,ch1;
ch=getch();
ch1=getch();
printf("%c\n%c",ch,ch1);

When I press a arrow key which produces two outputs, the first output is stored in ch and the second output is stored in ch1.

manlio
  • 18,345
  • 14
  • 76
  • 126
kevin gomes
  • 1,775
  • 5
  • 22
  • 30

1 Answers1

0

Standard C input functions only start processing what you type in when you press the Enter key.

Every key you press adds a character to the system buffer (shell), but only when you press Enter these characters are MOVED to C standard buffer.

So after ch = getchar(); the C buffer contains a newline and the system buffer is empty. (getch(), which isn't a standard function, will read the system buffer).


In the second example, getch() function returns multiple keycodes for a special key (getch() isn't standardized and these codes might vary).

E.g.

  • MinGW / Visual C++ (conio.h): two keycodes. Either 0x00 or 0xE0 first and then the code identifying the key that was pressed.
  • GCC (termios.h): three keycodes. First '\033' (ESC), then '[', last the code identifying the key pressed.

Anyway using only getch() you're reading all the characters in the system buffer (without forcing a transfer to the C standard buffer).

manlio
  • 18,345
  • 14
  • 76
  • 126