We employ the getch function in a C/ C++ program to pause the output screen temporarily until the user presses a key on the keyboard to close the console screen. By utilizing the getch function, we can conceal the user's input characters, such as ATM PINs, passwords, etc., for security purposes.
Syntax:
int getch(void);
Parameters: The getch function does not receive any input from the user.
The return value of this function is the ASCII value corresponding to the key that the user has pressed as input.
Create a basic program that showcases the character input by the user utilizing the getch function in the C programming language.
Program.c
#include <stdio.h>
#include <conio.h>
int main()
{
printf(" Passed value by the User is: %c", getch()); // print a character entered by the user
return 0;
}
Output:
Passed value by the User is: P
To display a character on the console, simply press the key that corresponds to it.
Create a basic program that will keep the console window open until the user presses a key to close it.
Program2.c
#include <stdio.h>
#include <conio.h>
int main()
{
printf("Enter a key to exit the console screen.\n");
getch();
return 0;
}
Output:
Enter a key to exit the console screen.
Create a program that utilizes the getch function to receive input of a string from the user.
Usergetch.c
#include <stdio.h>
#include <conio.h>
int main() {
char ch[6] = {0}; int x;
for ( x = 0; x < 5; x++) {
ch[x] = getch(); // getch() function to take input
}
printf("Received 5 character Input: %s\n", ch);
return 0;
}
Output:
Received 5 character Input: hello
Create a program that utilizes the getch function to receive the concealed password input from the user.
Program3.c
#include<stdio.h>
#include<string.h>
#include<dos.h>
#include<conio.h>
void main()
{
char pw[10];
int x;
printf(" Enter password: ");
for (x = 0; x < 10; x++)
{
// accepts the hidden password using the getch() function
pw[x] = getch();
printf("*"); // print the input chartered in the form of *
}
pw[x] = '\0';
printf( "\n" );
printf(" You have passed the hidden password: ");
for (x = 0; pw[x] != '\0'; x++)
{
printf("%c", pw[x]);
}
getch();
}
Output:
Enter password: **********
You have passed the hidden password: Password@1