![]() |
VOOZH | about |
In C, getc(), getchar(), getch(), and getche() are all functions that is used to read input character in different contexts. Although these functions are used for similar purposes and have similar names, they have different behaviours and use cases.
The below table lists the primary differences between the getc(), getchar(), getch() and getche() in C:
| Function | Header File | Purpose | Input Source | Buffering | Return Type |
|---|---|---|---|---|---|
| getc() | <stdio.h> | Reads a character from a given file. | File stream | Buffered | int (ASCII value of the character) |
| getchar() | <stdio.h> | Reads a character from standard input. | Standard input (stdin) | Buffered | int (ASCII value of the character) |
| getch() | <conio.h> | Reads a single character from keyboard. | Keyboard | Unbuffered | char (character entered) |
| getche() | <conio.h> | Reads a single character from keyboard. | Keyboard | Unbuffered | char (character entered) |
The getc() function reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure.
Example:
Input
g (press enter key)Output
gExplanation: In this program, the getc() function reads a single character from the standard input (stdin). The entered character is immediately echoed to the screen and printed using printf().
The getchar() function reads a single input character from standard input. So getchar() is equivalent to getc(stdin).
Example:
Input
g (press enter key)Output
gExplanation: In this program, the getchar() function reads a single character from the standard input (stdin). The character is then printed using printf(), and it is echoed to the screen during input.
getch() is a non-standard library function that reads a single character from the keyboard. But it does not use any buffer, so the entered character does not display on the screen and is immediately returned without waiting for the enter key.
Example:
Input
(Just press g key)
Output
gExplanation: In this program, the getch() function reads a single character from the keyboard without displaying it on the screen. The character is then printed using printf(). Since getch() doesn't echo input, the character won't appear as the user types it.
getche() function reads a single character from the keyboard and displays immediately on the output screen without waiting for enter key. Like getch(), it is also a non-standard function present in <conio.h> header file.
Example:
Input
g (Just press g key)
Output
gExplanation: In this program, the getche() function reads a single character from the keyboard and immediately echoes it to the screen. The character is then printed using printf(), and it appears as the user types it.