Documentation · Chapter 14

Read input and produce clear output.

A terminal program follows a simple rhythm: display a prompt, read a line, normalize it, validate it, then print a result.

Every lesson starts from the problem, explains the mechanism, then gives a concrete verification.

LESSON OBJECTIVE

What you will be able to do

Read input safely, choose the correct output channel, validate values, and return meaningful exit statuses.

stdout, stderr, and stdin

echo writes normal output. STDERR is for diagnostics. fgets(STDIN) reads a line and may return false, so trim only after checking it.

phpaml — zsh
$line = fgets(STDIN);
if ($line === false) {
    fwrite(STDERR, "Input unavailable\n");
    exit(1);
}
$name = trim($line);

Validate after reading

A string from the terminal remains a string. Validate ranges and formats before converting or constructing domain objects.

Choose useful exit codes

Return 0 for success and a non-zero status for invalid usage or failure so scripts can react correctly.

CHECKPOINT

Before you continue

What happens when fgets returns false, the age is not numeric, or the program is used by another script?