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
- stdout is buffered; stderr is not, so errors appear immediately.
- Redirecting output leaves stderr on the terminal.
fflush(stdout)forces a prompt out before reading.
Keywords and builtins used here
ifintprompt_and_readreturn
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.
Step 2 of 3 in Positioning & streams, step 10 of 12 in Files & I/O.