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 toint
to 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
STDIN
option, 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
getchar
andgetc
.getchar
only takes a character from standard input, whereasgetc
can fetch a character from any input stream, e.g., files.
Free Resources