Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Differences between Difference between getc(), getchar(), getch() and getche() functions
All of these functions are used to read a character from input and each returns an integer value. They differ in where they read from, whether they use a buffer, and whether they echo the character to the screen.
getc()
getc() reads a single character from any input stream (file, stdin, etc.). It uses a buffer and waits for the Enter key. Returns EOF on failure.
Syntax −
int getc(FILE *stream);
getchar()
getchar() reads a single character from standard input only. It is equivalent to calling getc(stdin). It uses a buffer and waits for the Enter key.
Syntax −
int getchar();
getch()
getch() reads a character from standard input without buffering and returns immediately without waiting for the Enter key. It does not echo the character to the screen. This function is defined in <conio.h> and is non-standard (available on Windows/DOS).
Syntax −
int getch();
getche()
getche() behaves like getch() − it reads without buffering and returns immediately. The only difference is that it echoes the character to the screen. Also defined in <conio.h> and non-standard.
Syntax −
int getche();
Key Differences
| Function | Input Source | Buffered | Waits for Enter | Echoes Character | Header |
|---|---|---|---|---|---|
getc() |
Any stream | Yes | Yes | Yes | <stdio.h> |
getchar() |
stdin only | Yes | Yes | Yes | <stdio.h> |
getch() |
stdin only | No | No | No | <conio.h> |
getche() |
stdin only | No | No | Yes | <conio.h> |
Example
The following program demonstrates all four functions (requires <conio.h> support on Windows) ?
#include <stdio.h>
#include <conio.h>
int main() {
printf("getc: ");
printf("%c\n", getc(stdin)); // reads from stdin, waits for Enter
printf("getchar: ");
printf("%c\n", getchar()); // reads from stdin, waits for Enter
printf("getch: ");
printf("%c\n", getch()); // reads immediately, no echo
printf("getche: ");
printf("%c\n", getche()); // reads immediately, echoes character
return 0;
}
If the user types A (Enter), B (Enter), C, D, the output would be −
getc: A getchar: B getch: C getche: DD
Note − For getch(), the character C is not shown when typed but appears when printed. For getche(), the character D appears twice − once from the echo and once from the printf.
Conclusion
Use getc() for reading from any file stream, getchar() for standard input with buffering, getch() for unbuffered silent input, and getche() for unbuffered input with echo. Note that getch() and getche() are non-standard and only available on platforms that support <conio.h>.
