Code Snippets »
C/C++ Code Snippets
How to identify ENTER KEY is pressed in c programming language?
By: IncludeHelp On 20 DEC 2016
Here, we will learn how to get and identify that ENTER KEY is pressed?
We will read character by character in an infinite loop and print the input characters until ENTER KEY is not pressed.
Within the infinite loop there will be a condition to check whether input character is ENTER KEY or not, if ENTER KEY is pressed, loop will be terminated otherwise input character will be printed and ask for Input any character again?
Condition to check ENTER KEY
There are basically two methods to check input key is ENTER KEY of not
- By checking ASCII Code
- By checking new line character '\n'
By checking ASCII Code
The ASCII Code of ENTER KEY is 10 in Decimal or 0x0A in Hexadecimal.
Let suppose input character is storing in variable ch, then condition will be as below
By checking New line character '\n'
We can also check that Input character is new line or not by comparing input character is equal to '\n' or not.
Let’s consider the following program
printf("Enter any character: ");
//read a single character
printf("ENTER KEY is pressed.\n");
printf("%c is pressed.\n",ch);
//read dummy character to clear
//input buffer, which inserts after character input
Enter any character: A
A is pressed.
Enter any character: B
B is pressed.
Enter any character: 9
9 is pressed.
Enter any character:
ENTER KEY is pressed.