CKTIS / C
getchar — C23 stream function
`getchar()` from `<stdio.h>` obtains the next character from standard input and is equivalent to `getc(stdin)`. It returns the character read as an `unsigned char` converted to `int`, or the `EOF` macro value when end-of-file or a read error occurs.
Version: C23
Syntax
int getchar(void);getchar() from <stdio.h> obtains the next character from standard input and is equivalent to getc(stdin). It returns the character read as an unsigned char converted to int, or the EOF macro value when end-of-file or a read error occurs.
The example pushes Q back onto stdin with ungetc, then actually consumes it through getchar. Output Q 81 shows both the character and its value in the execution character set; the program checks that ungetc succeeded before reading.
Store the result in int, not char, or the ability to distinguish EOF can be lost. EOF alone does not reveal whether the cause was data exhaustion or an error: test feof(stdin) and ferror(stdin) respectively, and use clearerr to clear those indicators. An implementation may also provide a macro; (getchar)() suppresses it and calls the actual function declared by the header.
Examples
#include <stdio.h>
int main(void){if(ungetc('Q',stdin)==EOF)return 1;int character=getchar();if(character==EOF)return 1;printf("%c %d\n",character,character);return 0;}
Result
Q 81
The example pushes `Q` back onto `stdin` with `ungetc`, then actually consumes it through `getchar`. Output `Q 81` shows both the character and its value in the execution character set; the program checks that `ungetc` succeeded before reading.