C:C Standard I/O: printf and scanf Formatting Guide
C•Input/Output

C Standard I/O: printf and scanf Formatting Guide

Learn formatting flags, reading variables via memory addresses with scanf(&var), and buffer handling with fgets.

Syntax

printf("Format %d", val); scanf("%d", &variable);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
scanfFunctionReads formatted input from stdin into variable pointers.
&Address-of OperatorSupplies memory address of variable to scanf.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

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

int main(void) {
    char hostname[64] = "api.compilra.internal";
    int port = 443;
    float latencyMs = 12.45f;

    // Formatted output with column width and precision
    printf("%-24s %-8s %-12s\n", "HOST", "PORT", "LATENCY");
    printf("%-24s %-8d %-10.2fms\n", hostname, port, latencyMs);

    return 0;
}
Expected Output:
HOST                     PORT     LATENCY     
api.compilra.internal    443      12.45     ms

How It Works: Step-by-Step

  • Lines 5-7: Initializes string and numeric variables.
  • Lines 10-11: Uses field-width formatting %-24s for left-aligned tabular printing.

Key Concepts

  • printf format flags like %-24s align strings cleanly in fixed-width columns.
  • scanf requires memory addresses (&var) to store parsed values.
  • Prefer fgets(buf, sizeof(buf), stdin) over gets() or raw scanf("%s") to prevent buffer overflows.

Common Mistake: Omitting the address-of & operator in scanf for primitive variables

Passing a variable by value to scanf causes a segmentation fault crash when it writes to invalid memory.

❌ Incorrect
int age;
scanf("%d", age); // Segmentation Fault! Missing &
✅ Correct
int age;
scanf("%d", &age); // Correctly passes pointer to age

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler