- Asked 2/16
- 2071 Shrawan · 1 mark
- 2071 Chaitra · 1 mark
Syntax and example of getch()
Short answer
getch() (from <conio.h>) reads a single keypress without echoing and without waiting for Enter. Syntax: ch = getch();. Used for password input or to hold the screen; for standard C, getchar() provides similar functionality but requires Enter and echoes.
Write syntax, example and use of getch().
getch() reads one character from the keyboard without displaying it (no echo) and without waiting for the Enter key. It is declared in <conio.h> (a non-standard header of Turbo C and Windows compilers).
Syntax: ch = getch(); or simply getch();
Example (Turbo C):
char ch;
printf("Enter password character: ");
ch = getch(); /* key is read but not shown */
printf("\nYou pressed %c", ch);
Uses:
- reading passwords and secret input, since typed characters are not echoed;
- holding the output screen until a key is pressed (
getch();at the end ofmain); - menu choices that should react on a single keypress.
conio.h is not available in gcc. The portable standard function getchar() does the same job but needs the Enter key and echoes the character:
#include <stdio.h>
int main(void)
{
char ch;
printf("Press a key: ");
ch = getchar(); /* portable counterpart of getch()/getche() */
printf("You pressed: %c\n", ch);
return 0;
}
Output for the key k:
Press a key: You pressed: k
✓ Answer checked by Claude Opus 5.5 (high effort)