getchar() & putchar()
getchar() and putchar(), both declared in <stdio.h>, are the simplest character-level I/O functions in C. getchar() reads a single character from standard input, and putchar() writes a single character to standard output. Together they are the building blocks for processing text one character at a time.C
#include <stdio.h>
int main(void) {
printf("Type a character: ");
int c = getchar();
printf("You typed: ");
putchar(c);
putchar('\n');
return 0;
}getchar() Returns int, Not char
This matters for correctly detecting EOF
getchar() is declared to return an int, not a char. This is deliberate: it needs to represent every possible unsigned char value plus one extra, distinct value, EOF (typically -1), to signal end-of-input or an error. If you store the result in a plain char variable, on platforms where char is unsigned, a legitimate character value could be mistaken for EOF, or EOF itself could get truncated into a valid-looking character — breaking the end-of-input check entirely. Always store the result in an int.C
char c = getchar(); // BUG RISK: narrowing to char can corrupt the EOF check
if (c == EOF) { /* may never trigger correctly on some platforms */ }
int cCorrect = getchar(); // CORRECT: int can hold every char value plus EOF
if (cCorrect == EOF) { /* reliable */ }The Classic Read-Until-EOF Loop
A very common C pattern reads characters one at a time until
EOF is reached, doing some work with each character along the way.C
#include <stdio.h>
int main(void) {
int c;
int count = 0;
while ((c = getchar()) != EOF) {
putchar(c); // echo the character back out
count++;
}
printf("\nRead %d characters\n", count);
return 0;
}Note
The assignment
(c = getchar()) inside the loop condition is a deliberate, idiomatic use of assignment-as-expression: it reads one character, stores it in c, and the whole expression evaluates to that same value for the != EOF comparison. The parentheses are required — without them, c = getchar() != EOF would first compare getchar() to EOF and then assign the boolean result (0 or 1) to c, which is not what you want.getchar()reads one character from stdin;putchar()writes one character to stdoutgetchar()returnsint, notchar, specifically so it can representEOFunambiguouslyAlways store the result of
getchar()in anintvariable, never a plaincharwhile ((c = getchar()) != EOF)is the standard idiom for processing input one character at a time