getchar and putchar
- C course
- Beginner
- Lesson 33/116
- 5 min
Learn to read and write single characters with getchar and putchar.
getchar and putchar
getchar() reads a single character from the keyboard and returns it as an int. putchar(c) writes a single character to the screen. They are simpler and faster than scanf and printf.
int c = getchar();
putchar(c);The user types a letter and presses Enter; getchar takes the first character. The return type is int, not char, because at end-of-file it can return EOF (usually -1). This distinction matters in comparisons.
A character loop
getchar and putchar together form a simple character echo program. You stop the loop when EOF is returned.
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}This loop echoes every typed character until the user presses Ctrl+D (Linux/Mac) or Ctrl+Z (Windows). You'll see the loop condition in detail in the next section.
Practice Echo a character
Write a C program. Declare int c;. Read a character with c = getchar();. Print the same character with putchar(c);. Then move to a new line with putchar('\n');. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare c, read with getchar, write with putchar
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int c;
c = getchar();
putchar(c);
putchar('\n');
return 0;
}Expected output
A
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match character I/O
| Term | Meaning |
|---|---|
getchar() |
Reads a character |
putchar(c) |
Writes a character |
int c |
getchar return type |
EOF |
End of file |
2 What does getchar() return?
int c = getchar();- A string
- A single character (as int) Correct answer
- Only a char
- An array of integers
Explanation: getchar returns one character as an int.
3 Print the character
int c = getchar();
____(c);
int c = getchar();
putchar(c);
Explanation: putchar(c) writes the character to the screen.