0
0
CHow-ToBeginner · 3 min read

How to Use getchar and putchar in C: Simple Input and Output

In C, getchar() reads a single character from the keyboard input, and putchar() writes a single character to the output (usually the screen). You use getchar() to capture user input one character at a time and putchar() to display characters, often in loops for processing text.
📐

Syntax

getchar() reads the next character from standard input and returns it as an int. It returns EOF (end-of-file) when no more input is available.

putchar(int char) writes the character given by the integer char to standard output and returns the character written.

c
int getchar(void);
int putchar(int char);
💻

Example

This example reads characters from the keyboard until you press Enter (newline), then prints each character back to the screen.

c
#include <stdio.h>

int main() {
    int ch;
    printf("Type some text and press Enter:\n");
    while ((ch = getchar()) != '\n' && ch != EOF) {
        putchar(ch);
    }
    putchar('\n');
    return 0;
}
Output
Type some text and press Enter: Hello World Hello World
⚠️

Common Pitfalls

  • Forgetting that getchar() returns an int, not a char, to handle EOF correctly.
  • Not checking for EOF can cause infinite loops or errors.
  • Using putchar() with values outside the valid character range can cause unexpected output.
  • Mixing buffered input (like scanf) and getchar() without clearing input buffer may cause confusion.
c
#include <stdio.h>

int main() {
    int ch;
    printf("Enter characters, press Ctrl+D (Unix) or Ctrl+Z (Windows) to end:\n");
    while ((ch = getchar()) != EOF) {
        putchar(ch); // Correct: ch is int to handle EOF
    }
    return 0;
}
Output
Enter characters, press Ctrl+D (Unix) or Ctrl+Z (Windows) to end: Hello Hello
📊

Quick Reference

FunctionPurposeReturn Value
getchar()Reads one character from inputCharacter as int or EOF
putchar(int char)Writes one character to outputCharacter written or EOF

Key Takeaways

Use getchar() to read one character at a time from keyboard input.
Use putchar() to print one character at a time to the screen.
Always store getchar() result in an int to detect EOF properly.
Check for EOF to avoid infinite loops when reading input.
putchar() outputs the character corresponding to the int value given.