getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX.
Like these functions, getch() also reads a single character from the keyboard. But it does not use any buffer, so the entered character is immediately returned without waiting for the enter key.
Syntax:
int getch(void);
Parameters: This method does not accept any parameters.
Return value: This method returns the ASCII value of the key pressed.
Example:
C
#include <stdio.h>
#include <conio.h>
int main()
{
printf ( "%c" , getch());
return 0;
}
|
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
Important Points regarding getch() method:
- getch() method pauses the Output Console until a key is pressed.
- It does not use any buffer to store the input character.
- The entered character is immediately returned without waiting for the enter key.
- The entered character does not show up on the console.
- The getch() method can be used to accept hidden inputs like password, ATM pin numbers, etc.
Example: To accept hidden passwords using getch()
Note: Below code won’t run on Online compilers, but on MS-DOS compilers like Turbo IDE.
C
#include <conio.h>
#include <dos.h> // delay()
#include <stdio.h>
#include <string.h>
void main()
{
char pwd[9];
int i;
clrscr();
printf ( "Enter Password: " );
for (i = 0; i < 8; i++) {
pwd[i] = getch();
printf ( "*" );
}
pwd[i] = '\0' ;
printf ( "\n" );
printf ( "Entered password: " );
for (i = 0; pwd[i] != '\0' ; i++)
printf ( "%c" , pwd[i]);
getch();
}
|
Output:
Abcd1234
Output:
Enter Password: ********
Entered password: Abcd1234
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Nov, 2023
Like Article
Save Article