Input and Output

Article · 3:00

printf and scanf, the format specifiers, and why scanf is the wrong tool for reading a line.

printf writes formatted text. Its first argument is a format string in which % introduces a placeholder, and the rest of the arguments fill them in order. The specifier must match the argument's type: %d for int, %u for unsigned, %ld for long, %f for double, %c for char, %s for a string, %p for a pointer, %zu for a size_t. A mismatch is undefined behaviour, not a conversion - printf("%d", 3.5) does not print 3, it prints whatever reading those bytes as an int produces.

scanf reads formatted input and is the source of more beginner frustration than anything else in C. Three facts explain most of it. It needs the address of what it is filling, so scanf("%d", &n) and not scanf("%d", n). It leaves the newline in the buffer, so a following %c or getchar reads the Enter key you pressed. And %s stops at whitespace and has no length limit, which makes it a buffer overflow waiting for a long word.

For reading a line, use fgets, which takes a maximum length and cannot overflow. Converting the result with strtol rather than atoi also tells you whether the conversion succeeded, which atoi does not.

printf returns the number of characters written, and scanf returns the number of items successfully assigned. Checking that return value is how you tell the difference between a user who typed a number and one who typed their name.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    /* The specifier must match the TYPE. A mismatch is undefined
       behaviour - the bytes are reinterpreted, not converted. */
    int    n      = 42;
    double d      = 3.14159;
    char   c      = 'x';
    char  *s      = "text";
    size_t length = strlen(s);

    printf("%d | %u | %ld | %f | %.2f | %c | %s | %p | %zu\n",
           n, 7u, 1234567890L, d, d, c, s, (void *) s, length);

    printf("|%5d|%-5d|%05d|\n", 42, 42, 42);   /* width, left, zero-pad */
    printf("a tab\there, a percent sign %%, a newline next\n");

    /* scanf wants the ADDRESS, and returns how many items it assigned. */
    int age;
    printf("Age: ");
    if (scanf("%d", &age) != 1) {
        fprintf(stderr, "that was not a number\n");
        return 1;
    }

    /* And it left the newline behind, so this would read Enter. */
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) { /* discard it */ }

    /* For a line, fgets - it takes a size and cannot overflow.
       scanf("%s", name) has no length limit at all. */
    char name[64];
    printf("Name: ");
    if (fgets(name, sizeof name, stdin) != NULL) {
        name[strcspn(name, "\n")] = '\0';   /* fgets keeps the newline */
        printf("Hello, %s (age %d)\n", name, age);
    }
    return 0;
}