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
Selected Reading
Difference between getc(), getchar(), getch() and getche()
All these functions read characters from input and return an integer. They differ in their source, buffering behavior, and echo characteristics.
Syntax
int getc(FILE *stream); int getchar(void); int getch(void); /* Non-standard */ int getche(void); /* Non-standard */
getc()
The getc() function reads a single character from a specified file stream and returns it as an integer. It waits for the Enter key and uses buffered input.
Example
#include <stdio.h>
int main() {
char val;
printf("Enter the character: ");
val = getc(stdin);
printf("Character entered: %c<br>", val);
return 0;
}
Enter the character: a Character entered: a
getchar()
The getchar() function reads a character from standard input (keyboard). It is equivalent to getc(stdin) and also waits for the Enter key with buffered input.
Example
#include <stdio.h>
int main() {
char val;
printf("Enter the character: ");
val = getchar();
printf("Entered character: %c<br>", val);
return 0;
}
Enter the character: b Entered character: b
Standard Alternative for getch() and getche()
Note: getch() and getche() are non-standard functions available only in some compilers (Turbo C, older Windows compilers). They require conio.h which is not part of standard C. Since these functions are not portable, here's how to achieve similar behavior using standard C:
Example: Simulating getch() Behavior
#include <stdio.h>
int main() {
char val;
printf("Enter a character (press Enter): ");
val = getchar();
printf("You entered: %c<br>", val);
return 0;
}
Enter a character (press Enter): x You entered: x
Key Differences
| Function | Input Source | Buffered | Echo | Standard |
|---|---|---|---|---|
getc() |
Any file stream | Yes | Yes | Yes |
getchar() |
stdin only | Yes | Yes | Yes |
getch() |
Keyboard | No | No | No |
getche() |
Keyboard | No | Yes | No |
Conclusion
Use getc() for file input and getchar() for standard input. Avoid non-standard getch() and getche() for portable code. All return EOF on failure or end-of-file.
Advertisements
