typestar

The three standard streams in C

stdin, stdout and stderr, and why diagnostics belong on the third.

#include <stdio.h>

int prompt_and_read(int *out) {
    printf("value: ");
    fflush(stdout);

    if (scanf("%d", out) != 1) {
        fprintf(stderr, "not a number\n");
        return 0;
    }
    fprintf(stdout, "read %d\n", *out);
    return 1;
}

How it works

  1. stdout is buffered; stderr is not, so errors appear immediately.
  2. Redirecting output leaves stderr on the terminal.
  3. fflush(stdout) forces a prompt out before reading.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
211
Tokens
69
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 41 seconds.

Type this snippet

Step 2 of 3 in Positioning & streams, step 10 of 12 in Files & I/O.

← Previous Next →