typestar

Reading input safely in C

scanf is sharp: check its return value, and never let %s run unbounded.

#include <stdio.h>

void read_pair(void) {
    int count = 0;
    double rate = 0.0;

    printf("count and rate: ");
    if (scanf("%d %lf", &count, &rate) != 2) {
        printf("could not read both values\n");
        return;
    }

    char name[10];
    if (scanf("%9s", name) == 1) {
        printf("%s: %d at %.1f\n", name, count, rate);
    }
}

How it works

  1. It returns the number of items successfully assigned.
  2. %9s bounds the write to a ten-byte buffer.
  3. Most real code reads a line with fgets and parses that instead.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
296
Tokens
93
Three-star pace
90 tpm

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

Type this snippet

Step 2 of 2 in Input & output, step 32 of 35 in Language basics.

← Previous Next →