HP C/iX Library Reference Manual (30026-90004)
Chapter 5 195
HP C/iX Library Function Descriptions
getchar
getchar
Reads a character from the standard input stream stdin.
Syntax
include <stdio.h>
int getchar (void);
Parameters
None.
Return Values
x The character read from stdin.
EOF Either an end-of-file was detected or an error occurred.
Description
The getchar function reads one character from the standard input stream stdin.
The getchar function returns the next character in the currently defined stdin stream. It
returns an EOF on end-of-file or file read error. The getchar function is identical to getc
(stdin).
Examples
The following program reads stdin and echos the contents to stdout. The program ends
when an end of file is encountered on stdin.
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF)
putchar(c);
putchar('\n');
}
The variable c is declared as an int type instead of char because sign extension, bit
shifting, and similar operations can cause unexpected results with the char type. EOF is
defined as a negative number. If EOF is assigned to a char variable, and chars are not
signed in the implementation, the comparison for EOF will never be true. Therefore, all
examples in this chapter use the int type.
The last putchar() statement in the program outputs a new line, so further output
appears at the beginning of a new line instead of at the end of the last line of output.
The getchar and putchar functions are most useful in filters (programs that accept and