What is getchar in C?

The getchar function is part of the <stdio.h> header file in C. It is used when single character input is required from the user. The function reads the input as an unsigned char; then it casts and returns as an int or an EOF.

EOF is returned if the end of file is reached or an error is encountered.

getchar casts to int to allow the representation of EOF, which cannot be represented using a char.

The illustration below shows how getchar works:

How does getchar work?

Declaration

The getchar function is declared as follows:

int getchar(void)

The getchar function takes no parameter.

Example

The code snippet belwo shows how getchar can be used:

Input your character using the STDIN option, then press Run.

#include<stdio.h> // Including header file
int main(){
int myChar; // creating a variable to store the input
myChar = getchar(); // use getchar to fetch input
printf("You entered: %c", myChar); // print input on screen
return 0;
}

Enter the input below

The output above shows a single character printed on-screen. In the case that multiple characters are input, we will only pick the first character.

There is a slight difference betweengetchar and getc. getchar only takes a character from standard input, whereas getc can fetch a character from any input stream, e.g., files.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved