getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C. It is included in the stdio.h header file.
The
getchar
function prototype is
int getchar(void);
Sample usage
The following program uses
getchar
to read characters into an array and print them out using the putchar function after an end-of-file character is found.
#include <stdio.h>
int main(void)
{
char str[1000];
int ch, n = 0;
while ((ch = getchar()) != EOF && n < 1000) {
str[n] = ch;
++n;
}
for (int i = 0; i < n; ++i)
putchar(str[i]);
putchar('\n'); /* trailing '\n' needed in Standard C */
return 0;
}
The program specifies the reading length's maximum value at 1000 characters. It will stop reading either after reading 1000 characters or after reading in an end-of-file indicator, whichever comes first.
Common mistake
A common mistake when using
getchar
is to assign the result to a variable of type
char
before comparing it to EOF.
The following example shows this mistake:
char c; while ((c = getchar()) != EOF) { /* Bad! */
putchar(c);
}
Consider a system in which