PadhaikoAll subjects

Input and Output

Computer Programming (ENCT 101)

Open in the Padhaiko app

4.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>:

Standard I/O Streams in C
StreamDefault DeviceTypical DirectionPrimary Functions
stdinKeyboardInput (read)scanf(), getchar(), fgets()
stdoutDisplay console / terminalOutput (write)printf(), putchar(), puts()
stderrDisplay console / terminalError output (unbuffered)fprintf(stderr, ...)

C provides two broad families of console I/O functions in <stdio.h>:


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.

Standard and Legacy Character I/O Functions
FunctionHeaderDescriptionBuffered / 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 stdoutPrints character immediately
getch() / getche()<conio.h> (DOS/Turbo C, non-standard)Reads a single keypress immediately without waiting for EnterUnbuffered; getch() does not echo, getche() echoes
putch(int ch)<conio.h> (non-standard)Outputs a single character to console in legacy DOS compilersLegacy 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[]).

Unformatted String I/O Functions
FunctionHeaderBehaviorSafety & Newline Handling
char *fgets(char *s, int n, FILE *stream)<stdio.h>Reads at most n - 1 characters from stdin until newline or EOFSafe (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 sizeUnsafe (causes buffer overflow); never use in modern C
AspectUnformatted I/OFormatted I/O
Data Types SupportedCharacters and strings onlyAll basic types (int, float, double, char, strings)
Format Control StringNone requiredUses % conversion specifiers, width, flags, precision
Whitespace Handling in Stringsfgets() reads spaces as part of the linescanf("%s", s) stops at the first whitespace character
Examplesgetchar(), 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

Components of a printf() Conversion Specification
ComponentMeaningCommon Options & Examples
FlagsControls alignment, sign, and padding- (left-align), + (always show +/- sign), 0 (zero-pad left), space (leading space for positive)
Field WidthMinimum 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 ModifierAdjusts size of integer or floating typeh (short), l (long / double in scanf), ll (long long), z (size_t)
Type SpecifierMandatory 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())

Definition

printf() and scanf() Signatures and Return Values

Important scanf() Rules and Pitfalls:

  1. Always pass addresses (&): Writing scanf("%d", n); instead of scanf("%d", &n); causes undefined behavior / crash because scanf needs the memory address of n.
  2. Whitespace and %c trap: Most specifiers (%d, %f, %s) automatically skip leading whitespace, whereas %c reads the very next character, including leftover spaces or '\n' from a previous Enter keypress. Place a leading space in the format string (scanf(" %c", &ch);) to skip leftover whitespace.
  3. Reading strings with spaces: scanf("%s", name); stops at spaces; use a scanset scanf(" %[^\n]", name); (with a field-width cap like %49[^\n]) or fgets() to read full multi-word lines.

Worked Examples

Example 1

1 (6 marks)

Determine the exact console output produced by each printf() statement below (use _ to mark visible blank spaces in your trace):

Formatted printf() Field Width, Flags, and PrecisionC
#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 before 42: [ 42].
  • [%-5d]: - flag left-aligns inside width 5 -> 3 trailing spaces after 42: [42 ].
  • [%05d]: 0 flag pads with leading zeros up to width 5 -> [00042].

Tracing Float and String Formatting:

  • [%8.2f]: 3.14 takes 4 columns; padded with 4 leading spaces -> [ 3.14].
  • [%.4s]: Prints at most 4 characters of "Computer" -> [Comp].
Answer:

Output (with _ indicating spaces):

Exact Formatted OutputText
[___42]
[42___]
[00042]
[____3.14]
[Comp]
Example 2

2 (6 marks)

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():

scanf() Return Value and Whitespace HandlingC
#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.

Answer:

Output:

Program OutputText
sum=20 ch=A
matched=3 printed=12
Example 3

3 (5 marks)

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).

Line Uppercase Filter Using getchar() and putchar()C
#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;
}
Answer:

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

Question 1

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.
Answer:

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.

Question 2

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():

  1. getchar() (<stdio.h>): Standard ANSI C function; echoes input, waits for Enter (line-buffered), returns int (handles EOF).
  2. getch() (<conio.h>): Non-standard DOS/Windows function; reads a key immediately without waiting for Enter and does not echo it on screen.
  3. 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.

Answer:

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.

Question 3

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:

  1. %+05d on 7: + forces the sign +, 0 pads zeros to width 5 -> +0007 (5 characters).
  2. %.2f on 12.346: rounds to 2 decimal places -> 12.35 (5 characters).
  3. %6s on "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.

Answer:

Output: |+0007|12.35|___IOE| followed by a newline. printf() returns 21.

Question 4

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'.

  1. scanf("%d", &n); consumes '2' and '5', stopping right before '\n', which remains in stdin.
  2. A subsequent scanf("%c", &ch); does not skip whitespace, so it immediately reads that leftover '\n' into ch without waiting for the user to type a letter.
  3. Adding a space (" %c") tells scanf() to discard zero or more whitespace characters (' ', '\t', '\n') before reading the next non-whitespace character into ch.
Answer:

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.

Question 5

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:

Reading Full Name Safely with scanf ScansetC
#include <stdio.h>

int main(void) {
    char name[40];
    printf("Enter full name: ");
    scanf(" %39[^\n]", name);
    printf("Student: %s\n", name);
    return 0;
}
Answer:

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.

← Operators and ExpressionsControl Structures →