C Notes
Learn character input/output functions getchar() and putchar() in C. Understand how they work, their relationship with stdin/stdout, buffered I/O, and practical examples for character processing.
When you need to read or write a single character at a time, getchar() and putchar() are your go-to functions. They're simpler than scanf() and printf(), faster for character-by-character processing, and form the building blocks for many text-processing programs. Understanding these functions also helps you grasp how buffered I/O works in C.
putchar() — Write a Single Character
putchar() writes a single character to standard output (the screen). It's declared in <stdio.h>.
int putchar(int character);It takes an integer (the ASCII value of the character) and returns the character written, or EOF on error.
Hello ABC Welcome to C!
getchar() — Read a Single Character
getchar() reads a single character from standard input (keyboard). It waits for the user to press Enter before processing input (line-buffered).
int getchar(void);It returns the character read as an int, or EOF if end of input is reached.
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
putchar('\n');
printf("ASCII value: %d\n", ch);
return 0;
}Enter a character: A You entered: A ASCII value: 65
Why getchar() Returns int, Not char
This is a common question. getchar() returns int because it needs to return both valid characters (0-255) AND the special value EOF (typically -1). If it returned char, you couldn't distinguish between a valid character with value 255 and EOF.
#include <stdio.h>
int main() {
int ch; // Must be int, not char!
printf("Enter text (Ctrl+D to end on Linux, Ctrl+Z on Windows):\n");
while ((ch = getchar()) != EOF) {
putchar(ch);
}
printf("\nEnd of input detected\n");
return 0;
}Enter text (Ctrl+D to end on Linux, Ctrl+Z on Windows): Hello World Hello World Bye Bye End of input detected
Buffered I/O Behavior
Standard input in C is typically line-buffered. This means getchar() doesn't receive characters one-by-one as you type them — it waits until you press Enter, then delivers the entire line one character at a time.
Type something and press Enter: Hi! Character 1: 'H' (ASCII: 72) Character 2: 'i' (ASCII: 105) Character 3: '!' (ASCII: 33) Total characters: 3
Practical Examples
Counting Characters, Words, and Lines
Enter text (Ctrl+D/Ctrl+Z to end): Hello World This is C programming Characters: 33 Words: 5 Lines: 2
Convert Lowercase to Uppercase
#include <stdio.h>
int main() {
int ch;
printf("Enter text (press Enter to process):\n");
while ((ch = getchar()) != '\n') {
if (ch >= 'a' && ch <= 'z') {
putchar(ch - 32); // Convert to uppercase
} else {
putchar(ch);
}
}
putchar('\n');
return 0;
}Enter text (press Enter to process): hello World 123! HELLO WORLD 123!
Copy Input to Output (Character Echo)
#include <stdio.h>
int main() {
int ch;
printf("Type text (Ctrl+D/Ctrl+Z to stop):\n");
printf("Each line will be echoed back:\n\n");
while ((ch = getchar()) != EOF) {
putchar(ch);
}
return 0;
}Remove Consecutive Duplicate Characters
#include <stdio.h>
int main() {
int ch, prev = -1;
printf("Enter text with duplicates:\n");
while ((ch = getchar()) != '\n') {
if (ch != prev) {
putchar(ch);
}
prev = ch;
}
putchar('\n');
return 0;
}Enter text with duplicates: aaabbcccdddeee abcde
Count Vowels and Consonants
Enter a line of text: Hello World 123! Vowels: 3 Consonants: 7 Digits: 3 Others: 3
getchar() for Pausing Program Execution
A common use of getchar() is to pause the program until the user presses Enter:
#include <stdio.h>
int main() {
printf("Processing data...\n");
printf("Step 1 complete.\n");
printf("\nPress Enter to continue...");
getchar();
printf("Step 2 complete.\n");
printf("All done!\n");
return 0;
}Processing data... Step 1 complete. Press Enter to continue... Step 2 complete. All done!
getchar() vs scanf("%c") vs getch()
| Function | Header | Buffered | Echo | Newline handling |
|---|---|---|---|---|
getchar() | <stdio.h> | Yes | Yes | Stays in buffer |
scanf("%c") | <stdio.h> | Yes | Yes | Can skip with space |
getch() | <conio.h> | No | No | Platform-specific |
getche() | <conio.h> | No | Yes | Platform-specific |
#include <stdio.h>
int main() {
char ch1, ch2;
// getchar() reads character including whitespace
printf("Enter first char: ");
ch1 = getchar();
// Must consume the leftover newline!
while (getchar() != '\n'); // Flush buffer
printf("Enter second char: ");
ch2 = getchar();
printf("You entered: '%c' and '%c'\n", ch1, ch2);
return 0;
}Enter first char: A Enter second char: B You entered: 'A' and 'B'
Flushing the Input Buffer
After using getchar() or scanf(), leftover characters (especially \n) can cause issues. Here's how to flush the buffer:
#include <stdio.h>
void flushInput() {
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
int main() {
int num;
char ch;
printf("Enter a number: ");
scanf("%d", &num);
flushInput(); // Clear the leftover newline
printf("Enter a character: ");
ch = getchar();
printf("Number: %d, Character: '%c'\n", num, ch);
return 0;
}Enter a number: 42 Enter a character: X Number: 42, Character: 'X'
Interview Questions
Q1: Why does getchar() return int instead of char?
getchar() returns int to accommodate both valid character values (0-255) and the special EOF value (typically -1). If it returned char, there would be no way to distinguish between EOF and a valid character with value 255 (on systems where char is unsigned) or -1 (on systems where char is signed).
Q2: What is the difference between getchar() and scanf("%c")?
Both read a single character, but: (1) getchar() takes no arguments and always reads the next character including whitespace; (2) scanf(" %c", &ch) with a leading space skips whitespace characters. Also, getchar() returns the character as an int, while scanf stores it via a pointer.
Q3: How does line buffering affect getchar()?
Standard input is line-buffered by default. This means characters aren't delivered to getchar() until the user presses Enter. All characters typed on the line are buffered, and subsequent getchar() calls read from this buffer without waiting for more input — until the buffer is empty.
Q4: How do you properly read two characters using getchar()?
After reading the first character, you must consume the newline left by pressing Enter: either call getchar() again to discard it, or use a loop while(getchar() != '\n'); to flush the buffer. Then the second getchar() will correctly wait for new input.
Q5: Can putchar() print integers or strings?
No directly. putchar() prints a single character. To print an integer, you'd need to convert it to characters digit by digit. To print a string, loop through each character: while(*str) putchar(*str++);. For anything beyond single characters, use printf().
Summary
getchar()reads one character from stdin;putchar()writes one character to stdoutgetchar()returnsint(notchar) to distinguish valid characters fromEOF- Standard input is line-buffered — characters are delivered only after Enter is pressed
- Always check for
EOFin loops that read until end-of-input - The leftover newline after input is a common source of bugs — flush the buffer
- These functions are ideal for character-by-character text processing programs
- They're simpler and faster than
scanf/printffor single character operations
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for getchar() and putchar() in C Programming.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, input, output, getchar, and, putchar
Related C Programming Topics