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:
| Parameter | Type | Description |
|---|---|---|
| scanf | Function | Reads formatted input from stdin into variable pointers. |
| & | Address-of Operator | Supplies memory address of variable to scanf. |
Ready-to-Run Code Example
Executable in CompilraRun 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 ageRelated C Tutorials & Compiler
C Stdin Input: Using scanf(), fgets(), and sscanf() Safely
Parse structured numeric and string inputs from stdin in GNU GCC 14 using bounded scanf format specifiers and return-value checks.
C Primitive Data Types and Explicit Format Specifiers
Master C primitive types (int, float, double, char, unsigned long), sizeof memory allocation, and explicit printf format specifiers.
C Type Casting: Explicit Type Conversion with Examples
Convert data types in C explicitly using (target_type) and understand integer promotions.
C Strings: Null-Terminated Character Arrays (char[])
Master null-terminated strings (\0), strlen, strcpy, strcat, and strcmp from string.h.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.