The getchar() function in C is a standard library function used to read a single character from the standard input device (keyboard). It is commonly used for simple character-based input operations.
- Reads one character at a time from the standard input stream (
stdin). - Defined in the
<stdio.h>header file.
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
return 0;
}
Output
Enter a character: You entered: �
Syntax
int getchar(void);
getchar() function does not take any parameters.
Return Value
- Returns the entered character as an integer (int) representing its ASCII value.
- Returns EOF (End Of File) if the end of the input stream is reached or an input error occurs.
Examples of C getchar Function
The following C programs demonstrate the use of getchar() function
Example 1: Read a single character using getchar() function.
#include <stdio.h>
// Driver code
int main()
{
int character;
character = getchar();
printf("The entered character is : %c", character);
return 0;
}
Input
fOutput
The entered character is : fExample 2: Program to implement putchar to print the character entered by the user:
#include <stdio.h>
// Driver code
int main()
{
int character;
printf("Enter any random character between a-z: ");
character = getchar();
printf("The entered character is : ");
putchar(character);
return 0;
}
Input
Enter any random character between a-z: kOutput
The entered character is : kExample 3: Reading multiple characters using getchar()
#include <stdio.h>
// Driver code
int main()
{
int s = 13;
int x;
while (s--) {
x = getchar();
putchar(x);
}
return 0;
}
Input
geeksforgeeksOutput
geeksforgeeksExample 4: Read sentences using getchar() function and do-while loop.
#include <stdio.h>
// Driver code
int main() {
int ch, i = 0;
char str[150];
printf("Enter the characters\n");
do {
// Read character from input
ch = getchar();
// Store character in array
str[i] = ch;
// Increment index
i++;
} while (i < 149 && ch != '\n');
// Add null character at end
str[i] = '\0';
printf("Entered characters are %s", str);
return 0;
}
Input
Enter the characters
Welcome to GeeksforGeeksOutput
Entered characters are Welcome to GeeksforGeeks