C Basics · beginner · ~10 min

Reading input with scanf

Read numeric and string input from stdin safely.

Lesson

scanf reads formatted input from stdin and writes through the addresses of variables (note the &). Like printf, it uses format specifiers — and like printf, it is a magnet for bugs because it does almost no error checking.

Always check scanf's return value — the number of fields it successfully parsed. For reading lines safely, prefer fgets over scanf("%s", ...) which has no length limit.

Code examples

int a, b;
if (scanf("%d %d", &a, &b) == 2) {
    printf("%d\n", a + b);
} else {
    fprintf(stderr, "bad input\n");
    return 1;
}

Common mistakes

  • Forgetting the & — passing the value, not the address, corrupts memory.
  • scanf("%s", buf) reads until whitespace with no length cap → buffer overflow. Use "%99s" with a 100-byte buffer, or switch to fgets.