Standard I/O in C
Input and output in C revolve around the
<stdio.h> library. Unlike higher-level languages with simple print() functions, C gives you precise control over how data is formatted and displayed.Output with printf
printf (print formatted) writes formatted output to the standard output stream (stdout).c
Format Specifiers
Format specifiers tell
printf how to interpret and display each argument:| Specifier | Type | Example Output |
|---|---|---|
%d or %i | int | 42 |
%u | unsigned int | 42 |
%f | float / double | 3.140000 |
%e | Scientific notation | 3.140000e+00 |
%c | char | A |
%s | String (char*) | Hello |
%p | Pointer address | 0x7ffeabc |
%x | Hexadecimal | 2a |
%o | Octal | 52 |
%ld | long | 9000000000 |
%lld | long long | 9223372036854775807 |
%zu | size_t | 8 |
%% | Literal % | % |
Formatting Width and Precision
You can control the width, alignment, and precision of output:
c
Escape Sequences
| Sequence | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
\0 | Null character |
\r | Carriage return |
\a | Alert (beep) |
c
Input with scanf
scanf (scan formatted) reads formatted input from the standard input stream (stdin). It requires pointers to the variables where data should be stored.c
Critical Warning:scanf("%s", name)stops reading at the first whitespace. For full-line input, usefgets()instead.
Reading Full Lines with fgets
c
Best Practice: Preferfgetsoverscanffor string input.scanf("%s")is vulnerable to buffer overflow attacks and cannot read spaces.
Character I/O
For single characters, use
getchar() and putchar():c
The puts and gets Functions
c
Warning:gets()was removed from the C11 standard because it cannot prevent buffer overflows. Always usefgets()instead.
sprintf and sscanf — String Formatting
These work like
printf and scanf but operate on strings instead of the console:c
Tip: For safety, usesnprintfinstead ofsprintfto prevent buffer overflows:c
Practical Example: Mini Calculator
c
Summary
| Function | Purpose | Safe? |
|---|---|---|
printf | Formatted output to console | ✅ |
scanf | Formatted input from console | ⚠️ Use with care |
fgets | Read full line from input | ✅ Recommended |
puts | Print string + newline | ✅ |
getchar / putchar | Single character I/O | ✅ |
sprintf / snprintf | Format into a string | Use snprintf |
sscanf | Parse from a string | ✅ |