What are reading and writing characters in C language?

In C programming language, reading and writing characters are fundamental I/O operations that allow programs to interact with users through the console.

Syntax

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

Character Input/Output Functions

C provides several functions for character I/O operations −

  • getchar() − Reads a character from standard input (keyboard)
  • putchar() − Writes a character to standard output (screen)
  • getche() − Reads a character with echo (non-standard, conio.h)
  • getch() − Reads a character without echo (non-standard, conio.h)

Example: Basic Character Reading and Writing

This example demonstrates reading characters and converting their case −

#include <stdio.h>
#include <ctype.h>

int main() {
    char ch;
    
    printf("Enter characters (press Enter after each, type '.' to stop):<br>");
    
    while ((ch = getchar()) != '.') {
        if (ch == '<br>') {
            continue; /* Skip newline characters */
        }
        
        if (islower(ch)) {
            putchar(toupper(ch));
        } else if (isupper(ch)) {
            putchar(tolower(ch));
        } else {
            putchar(ch);
        }
        putchar('<br>');
    }
    
    printf("Program ended.<br>");
    return 0;
}
Enter characters (press Enter after each, type '.' to stop):
a
A
B
b
5
5
.
Program ended.

Example: Character Echo Program

This example shows how to read and immediately display characters −

#include <stdio.h>

int main() {
    char ch;
    int count = 0;
    
    printf("Enter text (type 'q' to quit):<br>");
    
    while ((ch = getchar()) != 'q') {
        if (ch != '<br>') {
            printf("You typed: ");
            putchar(ch);
            printf(" (ASCII: %d)<br>", ch);
            count++;
        }
    }
    
    printf("\nTotal characters entered: %d<br>", count);
    return 0;
}
Enter text (type 'q' to quit):
A
You typed: A (ASCII: 65)
5
You typed: 5 (ASCII: 53)
q

Total characters entered: 2

Key Differences

Function Buffered Echo Header File Standard
getchar() Yes Yes stdio.h Standard C
getche() No Yes conio.h Non-standard
getch() No No conio.h Non-standard

Key Points

  • getchar() waits for Enter key and reads buffered input
  • putchar() outputs one character at a time to the console
  • Both functions return int type to handle EOF (-1) condition
  • Use ctype.h functions like islower() and toupper() for character manipulation

Conclusion

Character I/O functions in C provide essential building blocks for console-based programs. The standard getchar() and putchar() functions offer portable solutions for reading and writing individual characters across different platforms.

Updated on: 2026-03-15T14:14:30+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements