Input and Output
Open in the Padhaiko app4.1 Introduction to data I/O in C
Unlike languages with built-in input/output keywords, C treats every I/O device (keyboard, screen, disk file) as a stream of bytes. When a C program starts, the runtime environment automatically opens three standard streams declared in <stdio.h>:
| Stream | Default Device | Typical Direction | Primary Functions |
|---|---|---|---|
stdin | Keyboard | Input (read) | scanf(), getchar(), fgets() |
stdout | Display console / terminal | Output (write) | printf(), putchar(), puts() |
stderr | Display console / terminal | Error output (unbuffered) | fprintf(stderr, ...) |
C provides two broad families of console I/O functions in <stdio.h>:
- Unformatted I/O: Reads or writes raw characters and strings directly without format conversion specifiers.
- Formatted I/O: Uses control strings (such as
%d,%f,%s) to parse text input into typed binary values or format binary values into readable text.
4.2 Unformatted I/O
Unformatted I/O functions work strictly with characters or character strings without format-string parsing. Because no conversion specifiers are interpreted, they are fast and lightweight.
4.2.1 Character I/O
Character I/O functions read or write a single character at a time.
| Function | Header | Description | Buffered / Echoed |
|---|---|---|---|
int getchar(void) | <stdio.h> | Reads next character from stdin (returns int so it can return EOF) | Line-buffered (waits for Enter); echoed |
int putchar(int ch) | <stdio.h> | Writes single character ch to stdout | Prints character immediately |
getch() / getche() | <conio.h> (DOS/Turbo C, non-standard) | Reads a single keypress immediately without waiting for Enter | Unbuffered; getch() does not echo, getche() echoes |
putch(int ch) | <conio.h> (non-standard) | Outputs a single character to console in legacy DOS compilers | Legacy only; prefer putchar() in ANSI C |
4.2.2 String I/O
String I/O functions read or write entire null-terminated character arrays (char str[]).
| Function | Header | Behavior | Safety & Newline Handling |
|---|---|---|---|
char *fgets(char *s, int n, FILE *stream) | <stdio.h> | Reads at most n - 1 characters from stdin until newline or EOF | Safe (prevents buffer overflow); keeps trailing '\n' if space allows |
int puts(const char *s) | <stdio.h> | Writes string s to stdout and automatically appends a newline '\n' | Safe and convenient for whole lines |
char *gets(char *s) (obsolete) | <stdio.h> (removed in C11) | Reads until newline without checking array size | Unsafe (causes buffer overflow); never use in modern C |
| Aspect | Unformatted I/O | Formatted I/O |
|---|---|---|
| Data Types Supported | Characters and strings only | All basic types (int, float, double, char, strings) |
| Format Control String | None required | Uses % conversion specifiers, width, flags, precision |
| Whitespace Handling in Strings | fgets() reads spaces as part of the line | scanf("%s", s) stops at the first whitespace character |
| Examples | getchar(), putchar(), fgets(), puts() | scanf(), printf() |
4.3 Formatted I/O
Formatted I/O converts between internal binary data types (int, float, double, char) and human-readable character representations using a control string (format string).
4.3.1 Control string (Flags, field width, precision, and specifier)
In printf(), a conversion specification inside the control string follows the general template:
%[flags][width][.precision][length]specifier
| Component | Meaning | Common Options & Examples |
|---|---|---|
| Flags | Controls alignment, sign, and padding | - (left-align), + (always show +/- sign), 0 (zero-pad left), space (leading space for positive) |
| Field Width | Minimum number of character columns printed | %5d prints 42 as 42 (padded with 3 spaces on left); %-5d prints 42 |
Precision (.p) | Digits after decimal point for floats, or max characters for strings | %.2f prints 3.14159 as 3.14; %.4s prints "Programming" as Prog |
| Length Modifier | Adjusts size of integer or floating type | h (short), l (long / double in scanf), ll (long long), z (size_t) |
| Type Specifier | Mandatory character defining data interpretation | %d/%i (int), %u (unsigned), %f (float/double), %lf (double in scanf), %c (char), %s (string), %o (octal), %x/%X (hex), %% (literal %) |
4.3.2 Formatted I/O (scanf(), printf())
printf() and scanf() Signatures and Return Values
int printf(const char *format, ...);Writes formatted output tostdoutaccording toformatand returns the total number of characters printed (or a negative value on error). Arguments are passed by value.int scanf(const char *format, ...);Reads formatted input fromstdinaccording toformatand stores converted values into memory using pointer addresses (&varfor scalar variables; array namestrwithout&for strings). Returns the number of input items successfully matched and assigned (orEOFon input failure).
Important scanf() Rules and Pitfalls:
- Always pass addresses (
&): Writingscanf("%d", n);instead ofscanf("%d", &n);causes undefined behavior / crash becausescanfneeds the memory address ofn. - Whitespace and
%ctrap: Most specifiers (%d,%f,%s) automatically skip leading whitespace, whereas%creads the very next character, including leftover spaces or'\n'from a previousEnterkeypress. Place a leading space in the format string (scanf(" %c", &ch);) to skip leftover whitespace. - Reading strings with spaces:
scanf("%s", name);stops at spaces; use a scansetscanf(" %[^\n]", name);(with a field-width cap like%49[^\n]) orfgets()to read full multi-word lines.
Worked Examples
1
Determine the exact console output produced by each printf() statement below (use _ to mark visible blank spaces in your trace):
#include <stdio.h>
int main(void) {
int n = 42;
double pi = 3.14159;
char word[] = "Computer";
printf("[%5d]\n", n);
printf("[%-5d]\n", n);
printf("[%05d]\n", n);
printf("[%8.2f]\n", pi);
printf("[%.4s]\n", word);
return 0;
}Tracing Integer Formatting (n = 42, 2 digits):
[%5d]: Minimum width 5, default right-aligned -> 3 leading spaces before42:[ 42].[%-5d]:-flag left-aligns inside width 5 -> 3 trailing spaces after42:[42 ].[%05d]:0flag pads with leading zeros up to width 5 ->[00042].
Tracing Float and String Formatting:
[%8.2f]:3.14takes 4 columns; padded with 4 leading spaces ->[ 3.14].[%.4s]: Prints at most 4 characters of"Computer"->[Comp].
Output (with _ indicating spaces):
[___42]
[42___]
[00042]
[____3.14]
[Comp]2
Trace what happens when a user enters 12 5 3 followed by Enter, and then enters A followed by Enter, in the following C program, including the return values of scanf() and printf():
#include <stdio.h>
int main(void) {
int a, b, c;
char ch;
int matched = scanf("%d %d %d", &a, &b, &c);
scanf(" %c", &ch);
int printed = printf("sum=%d ch=%c\n", a + b + c, ch);
printf("matched=%d printed=%d\n", matched, printed);
return 0;
}Tracing scanf("%d %d %d", &a, &b, &c);: scanf reads 12, 5, and 3 into a, b, and c, leaving the trailing newline '\n' in the stdin buffer. Because all three conversions succeeded, matched receives 3.
Tracing scanf(" %c", &ch);: The leading space inside " %c" instructs scanf to skip any leftover whitespace (including the buffered '\n'). It then reads 'A' into ch. Without that leading space, %c would have consumed '\n' instead of 'A'.
Tracing printf Character Count: "sum=20 ch=A\n" contains: s(1) u(2) m(3) =(4) 2(5) 0(6) (7) c(8) h(9) =(10) A(11) \n(12) = 12 characters.
Output:
sum=20 ch=A
matched=3 printed=123
Write a C program using unformatted character I/O (getchar() and putchar()) to read characters from standard input until a newline ('\n') is encountered, convert every lowercase letter to uppercase without <ctype.h>, and print the converted line.
ASCII Lowercase-to-Uppercase Logic: In ASCII, 'a'–'z' occupy codes 97–122 and 'A'–'Z' occupy 65–90, a constant offset of 32 ('a' - 'A'). Thus, if 'a' <= ch && ch <= 'z', subtracting ('a' - 'A') yields the uppercase equivalent.
Looping with int ch: Store the result of getchar() in an int variable so EOF and '\n' are handled safely, then output each character via putchar(ch).
#include <stdio.h>
int main(void) {
int ch;
printf("Enter a line: ");
while ((ch = getchar()) != '\n' && ch != EOF) {
if (ch >= 'a' && ch <= 'z') {
ch = ch - ('a' - 'A');
}
putchar(ch);
}
putchar('\n');
return 0;
}Use int ch; inside while ((ch = getchar()) != '\n' && ch != EOF), convert 'a'..'z' by subtracting ('a' - 'A'), and print with putchar(ch);.
Exercises
Exercises — Input and Output
Compare formatted I/O functions with unformatted I/O functions in C, giving two standard library examples of each.
Core Distinction:
- Formatted I/O (
printf(),scanf()) uses format specifiers (%d,%f,%s, flags, width, precision) to convert between internal binary representations and text, supporting any data type. - Unformatted I/O (
getchar(),putchar(),fgets(),puts()) transfers raw characters or character strings directly without format parsing.
Formatted I/O (printf(), scanf()) parses and formats multiple data types via % control strings, while unformatted I/O (getchar(), putchar(), fgets(), puts()) reads/writes raw characters and strings directly without conversion specifiers.
Differentiate between getchar(), getch(), and getche(). Why should portable ANSI C programs prefer getchar() or fgets() over <conio.h> functions and gets()?
Comparing getchar(), getch(), and getche():
getchar()(<stdio.h>): Standard ANSI C function; echoes input, waits for Enter (line-buffered), returnsint(handlesEOF).getch()(<conio.h>): Non-standard DOS/Windows function; reads a key immediately without waiting for Enter and does not echo it on screen.getche()(<conio.h>): Non-standard function; reads a key immediately without waiting for Enter and echoes it on screen.
Portability and Buffer Safety: <conio.h> is not part of the C standard and fails to compile on standard Linux/macOS toolchains. Likewise, gets() performs no bounds checking and allows buffer-overflow attacks (removed in C11), whereas fgets(buf, sizeof(buf), stdin) strictly bounds the input length.
getchar() is standard, buffered, and echoed; getch() is non-standard, unbuffered, and non-echoed; getche() is non-standard, unbuffered, and echoed. Standard C code avoids <conio.h> for portability and replaces gets() with fgets() to prevent buffer overflows.
Trace the exact output of the following C snippet (mark spaces with _): int x = 7; float y = 12.346; printf("|%+05d|%.2f|%6s|\n", x, y, "Institute of Engineering"); Also state the integer return value of this printf() call.
Evaluating Each Specifier:
%+05don7:+forces the sign+,0pads zeros to width 5 ->+0007(5 characters).%.2fon12.346: rounds to 2 decimal places ->12.35(5 characters).%6son"Institute of Engineering": right-aligned in 6 columns ->___IOE(3 spaces + 3 chars = 6 characters).
Counting Total Printed Characters: Output string: |+0007|12.35| Institute of Engineering|\n Character count: |(1) + +0007(5) + |(1) + 12.35(5) + |(1) + Institute of Engineering(6) + |(1) + \n(1) = 1 + 5 + 1 + 5 + 1 + 6 + 1 + 1 = 21 characters.
Output: |+0007|12.35|___IOE| followed by a newline. printf() returns 21.
Explain why scanf(" %c", &ch); often works reliably after reading a number with scanf("%d", &n);, whereas scanf("%c", &ch); skips user input.
Tracing the stdin Input Buffer: When the user types 25 and presses Enter, the input stream holds '2', '5', '\n'.
scanf("%d", &n);consumes'2'and'5', stopping right before'\n', which remains instdin.- A subsequent
scanf("%c", &ch);does not skip whitespace, so it immediately reads that leftover'\n'intochwithout waiting for the user to type a letter. - Adding a space (
" %c") tellsscanf()to discard zero or more whitespace characters (' ','\t','\n') before reading the next non-whitespace character intoch.
scanf("%d", &n) leaves the trailing '\n' in the input buffer. Because %c does not skip whitespace, scanf("%c", &ch) consumes that '\n'. Adding a leading space (" %c") skips any buffered whitespace first.
Write the purpose and syntax of scanf() scansets (%[...]) and field width specifiers in scanf() with a short C example that safely reads a student's full name (up to 39 characters, including spaces).
Scansets and Width Caps in scanf():
- A scanset
%[chars]matches only characters listed inside brackets, while%[^chars]matches every character except those listed (e.g.,%[^\n]reads until newline, preserving spaces). - Placing a maximum field width before the bracket (e.g.,
%39[^\n]for a 40-byte array) reserves 1 byte for the null terminator'\0'and prevents buffer overflow.
Example C Program:
#include <stdio.h>
int main(void) {
char name[40];
printf("Enter full name: ");
scanf(" %39[^\n]", name);
printf("Student: %s\n", name);
return 0;
}scanf(" %39[^\n]", name); skips leading whitespace, reads up to 39 characters including spaces until '\n', and automatically appends '\0', preventing overflow in a char name[40] array.