Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdio.h>
int getc(FILE *stream);
int getchar(void);
Reads a single character from the current stream position and advances the stream position to the next character. The getchar() function is identical to getc(stdin).
The getc() and fgetc() functions are identical. However, getc() and getchar() are provided in a highly efficient macro form. For performance purposes, it is recommended that the macro forms be used rather than the functional forms or fgetc(). By default, stdio.h provides the macro versions of these functions.
getc() and getchar() are not supported for files opened with type=record or type=blocked.
getc() and getchar() have the same restriction as any read operation for a read immediately following a write or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must also be an intervening flush or reposition unless an EOF has been reached.
If the application is not multithreaded, then setting the _ALL_SOURCE_NO_THREADS feature test macro may improve performance of the application, because it allows use of the inline version of this function.
getc() and getchar() return the character read.
A returned value of EOF indicates either an error or an EOF condition. If a read error occurs, the error indicator is set. If an EOF is encountered, the EOF indicator is set.
Use ferror() or feof() to determine whether an error or an EOF condition occurred. Note that EOF is only reached when an attempt is made to read past the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator.
⁄* CELEBG02
This example gets a line of input from the stdin stream.
You can also use getc(stdin) instead of &getchar. in the for
statement to get a line of input from stdin.
*⁄
#include <stdio.h>
#define LINE 80
int main(void)
{
char buffer[LINE+1];
int i;
int ch;
printf( "Please enter string\n" );
⁄* Keep reading until either:
1. the length of LINE is exceeded or
2. the input character is EOF or
3. the input character is a new-line character
*⁄
for ( i = 0; ( i < LINE ) && (( ch = getchar()) != EOF) &&
( ch !='\n' ); ++i )
buffer[i] = ch;
buffer[i] = '\0'; ⁄* a string should always end with '\0' ! *⁄
printf( "The string is %s\n", buffer );
}
Please enter string
hello world
The string is hello world