getchar Function in C (original) (raw)
Last Updated : 30 May, 2026
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. C++ `
#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.
C `
#include <stdio.h>
// Driver code int main() { int character; character = getchar();
printf("The entered character is : %c", character);
return 0;}
`
**Input
f
**Output
The entered character is : f
**Example 2: Program to implement putchar to print the character entered by the user:
C `
#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: k
**Output
The entered character is : k
**Example 3: Reading multiple characters using getchar()
C `
#include <stdio.h>
// Driver code int main() { int s = 13; int x; while (s--) { x = getchar(); putchar(x); } return 0; }
`
**Input
geeksforgeeks
**Output
geeksforgeeks
**Example 4: Read sentences using getchar() function and do-while loop.
C `
#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 GeeksforGeeks
**Output
Entered characters are Welcome to GeeksforGeeks