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.
EOFis returned if the end of file is reached or an error is encountered.
getcharcasts tointto allow the representation ofEOF, which cannot be represented using achar.
The illustration below shows how getchar works:
The getchar function is declared as follows:
int getchar(void)
The getchar function takes no parameter.
The code snippet belwo shows how getchar can be used:
Input your character using the
STDINoption, then pressRun.
#include<stdio.h> // Including header fileint main(){int myChar; // creating a variable to store the inputmyChar = getchar(); // use getchar to fetch inputprintf("You entered: %c", myChar); // print input on screenreturn 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 between
getcharandgetc.getcharonly takes a character from standard input, whereasgetccan fetch a character from any input stream, e.g., files.
Free Resources