Difference Between getch() and getche() in C

1. Introduction

In the C programming language, getch() and getche() are functions used to read a single character from the keyboard. They are part of the conio.h library and are commonly used in situations where immediate input from the keyboard is required.

2. Key Points

1. getch() reads a single character from the keyboard but does not echo the character to the console.

2. getche() is similar to getch() but it echoes the input character back to the console.

3. Neither getch() nor getche() require the Enter key to be pressed after the character input.

4. Both functions do not store the input character in the buffer, meaning they can handle input instantly.

3. Differences

getch() getche()
Does not echo the character to the console. Echoes the character to the console.
Used when the input character should not be displayed (like password input). Used when you need instant feedback of the typed character.

4. Example

#include <stdio.h>
#include <conio.h>

// Example using getch()
void usingGetch() {
    char ch;
    printf("Enter a character: ");
    ch = getch();
    printf("\nCharacter entered (not echoed): %c\n", ch);
}

// Example using getche()
void usingGetche() {
    char ch;
    printf("Enter a character: ");
    ch = getche();
    printf("\nCharacter entered (echoed): %c\n", ch);
}

int main() {
    usingGetch();
    usingGetche();
    return 0;
}

Output:

Enter a character:
Character entered (not echoed): a
Enter a character: a
Character entered (echoed): a

Explanation:

1. In usingGetch(), the character entered is not displayed on the console when the user types it.

2. In usingGetche(), the character is displayed (echoed) on the console as it is typed.

5. When to use?

- Use getch() when you do not want the input character to be displayed on the screen, like for password inputs.

- Use getche() when you need instant feedback for the input, such as in interactive command-line applications.

Comments