Consider the following program :

#include<iostream>

using namespace std;

int main()

{

char ch;

cout<<“Want to continue (Press: (y/n)) : ”;

cin>>ch;

return 0;

}

Now as the program runs, to input your choice , first you type the required character and then press the ‘enter’ key.

What if we want to eliminate the need of pressing the enter key?

For this purpose, we can use getche() and getch() functions.

> Both the functions take single character as input.

> getche() function echoes the character to the screen whereas getch() does not do so. This is the only difference between both the functions. It can be remembered by the use of character ‘e’ at the end of getche() function.

> Both takes no arguments and require ‘conio.h’ header file.

Now we write the above program with the help of getche() function :

#include<iostream>

using namespace std;

int main()

{

char ch;

cout<<“Want to continue (Press: (y/n)) : ”;

ch = getche();

return 0;

}

Now if you run the program, you will notice you no longer require to press the enter key after the character input. As soon as you enter the character, the value get stored in the variable and further lines of program start to execute.

You could have also used getch() instead of getche() function but the input character won’t be displayed in that case.

Since the value got stored in the variable, and further lines of code start to execute, this gives further rise to other potential uses. For example: The variable’s value can be checked using if-else/Decision control statements and certain action can be taken accordingly like termination of program and much more!

Our Products:

Product Name: “Don’t kill the Dream – Execute it” Classic Pullover Hoodie

Fit: Regular fit, kangaroo pocket, unisex

Click here to check out this Hoodie.

Product Name: “Pizza Any Time” Classic Crewneck Sweatshirt

Fit: Regular fit, unisex

Click here to check out this Sweatshirt.

Uses of getche() function in C++
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *