How to use printf and scanf

Print matching types

A format specifier must match the argument type. A mismatch can cause undefined behavior.

int count = 7;
double price = 2.5;
printf("Count: %d, price: %.2f\n", count, price);

Read and check a number

scanf returns the number of successful conversions. Pass an address with & and reject failed input.

int age;
printf("Age: ");
if (scanf("%d", &age) != 1) {
    fprintf(stderr, "Please enter a whole number.\n");
    return 1;
}

Limit text input

Never use unbounded %s. The field width must leave room for the terminating null byte.

char name[32];
if (scanf("%31s", name) == 1) {
    printf("Hello, %s\n", name);
}

Prefer fgets for lines

fgets knows the destination size and can read spaces. Check its return value; if no newline fits, the remaining input must be handled deliberately.

char line[128];
if (fgets(line, sizeof line, stdin) == NULL) {
    fprintf(stderr, "Input ended or failed.\n");
    return 1;
}