CC
BeginnerLesson 3 of 18

Input and Output: printf, scanf, fgets – C

Formatted output and safe keyboard input.

printf formats output using placeholders: %d (int), %u (unsigned), %ld (long), %f (double), %c (char), %s (string), %x (hexadecimal), %p (pointer), %zu (size_t), %% (percent sign). Between % and the letter you can put width, precision and flags.

#include <stdio.h>

int main(void) {
    int n = 42;
    double x = 3.14159;
    printf("[%5d] [%-5d] [%05d]\n", n, n, n);   // right-aligned, left-aligned, zero-padded
    printf("[%8.3f] [%.0f]\n", x, x);           // width 8, 3 decimal places
    printf("%c %s %x %X %o %%\n", 'Z', "Text", 255, 255, 8);
    return 0;
}

scanf reads formatted input. Important: it expects the address of the target variable (&) and returns the number of values read successfully – always check it!

#include <stdio.h>

int main(void) {
    int alter;
    printf("Age: ");
    if (scanf("%d", &alter) != 1) {
        fprintf(stderr, "Invalid input\n");
        return 1;
    }
    printf("Next year: %d\n", alter + 1);
    return 0;
}

For whole lines (including spaces), use fgets. It reads at most as many characters as fit into the buffer and keeps the newline – which you remove with strcspn.

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

int main(void) {
    char name[32];
    printf("Name: ");
    if (fgets(name, sizeof name, stdin) == NULL) return 1;
    name[strcspn(name, "\n")] = '\0';
    printf("Hello, %s!\n", name);
    return 0;
}
WarningNever use gets() (removed in C11) and never scanf("%s", puffer) without a width – both allow buffer overflows. Safe: fgets or scanf("%31s", puffer) for char puffer[32].
TipOutput to stdout is usually line-buffered. Error messages belong on stderr (fprintf(stderr, ...)) so that they can be redirected separately.