Input/Output in C
Make your programs interactive! Learn to display output with printf() and read user input with scanf(). Essential for every C program.
What You Will Learn
- ✓Display text and numbers with printf()
- ✓Use format specifiers (%d, %f, %c, %s)
- ✓Read user input safely with scanf()
- ✓Format output (decimals, width, alignment)
01What is Input/Output in C?
📺 Simple Definition
Input/Output (I/O) is how your program communicates with the outside world. Input = getting data IN (from keyboard, file). Output = sending data OUT (to screen, file).
📚 The stdio.h Header
All I/O functions come from the <stdio.h> header (Standard Input/Output).
#include <stdio.h>
📖 See the complete stdio.h Reference for all functions.
| Function | Purpose | Type |
|---|---|---|
| printf() | Print formatted output to screen | Output |
| scanf() | Read formatted input from keyboard | Input |
| getchar() | Read single character | Input |
| putchar() | Print single character | Output |
| gets() / fgets() | Read string (line) | Input |
| puts() | Print string with newline | Output |
02The printf() Function
📝 Syntax
printf("format string", value1, value2, ...);
The format string contains text and format specifiers (%d, %f, etc.)
📝 This program shows different ways to use printf for various data types.
1#include <stdio.h>23int main() {4 printf("Hello!\n"); // Text5 printf("Age: %d\n", 25); // Integer6 printf("Price: %.2f\n", 9.99); // Float7 printf("Grade: %c\n", 'A'); // Character8 printf("Name: %s\n", "Bob"); // String9 return 0;10}Hello!
Age: 25
Price: 9.99
Grade: A
Name: Bob
03Format Specifiers
🎯 What are Format Specifiers?
Format specifiers are placeholders that tell printf/scanf what type of data to expect and how to format it.
| Specifier | Data Type | Example | Output |
|---|---|---|---|
| %d or %i | int (signed) | printf("%d", 42) | 42 |
| %u | unsigned int | printf("%u", 42) | 42 |
| %ld | long int | printf("%ld", 123456789L) | 123456789 |
| %lld | long long int | printf("%lld", 9999999999LL) | 9999999999 |
| %f | float / double | printf("%f", 3.14) | 3.140000 |
| %.2f | float (2 decimals) | printf("%.2f", 3.14159) | 3.14 |
| %e | Scientific notation | printf("%e", 12345.67) | 1.234567e+04 |
| %c | char | printf("%c", 'A') | A |
| %s | string (char array) | printf("%s", "Hello") | Hello |
| %x / %X | Hexadecimal | printf("%x", 255) | ff |
| %o | Octal | printf("%o", 8) | 10 |
| %p | Pointer address | printf("%p", &x) | 0x7fff... |
| %% | Literal % | printf("100%%") | 100% |
📏 Width and Precision Modifiers
1#include <stdio.h>23int main() {4 printf("[%d]\n", 42); // Normal: [42]5 printf("[%5d]\n", 42); // Width 5: [ 42]6 printf("[%05d]\n", 42); // Zero-pad: [00042]7 8 printf("[%.2f]\n", 3.14159); // 2 decimals: [3.14]9 printf("[%8.2f]\n", 3.14); // Width 8: [ 3.14]10 return 0;11}[42]
[ 42]
[00042]
[3.14]
[ 3.14]
04printf Variants
| Function | Description | Use Case |
|---|---|---|
| printf() | Print to stdout (screen) | Normal console output |
| fprintf() | Print to file stream | Write to files, stderr |
| sprintf() | Print to string buffer | Format string in memory |
| snprintf() | Print to string (size limited) | Safe string formatting |
1#include <stdio.h>23int main() {4 char buf[50];5 6 printf("Hello!\n"); // To screen7 fprintf(stderr, "Error!\n"); // To stderr8 sprintf(buf, "Age: %d", 25); // To string9 printf("Buffer: %s\n", buf);10 11 return 0;12}Hello!
Error!
Buffer: Age: 25
💡 Always Use snprintf!
sprintf() can cause buffer overflow! Always prefer snprintf() which limits the output to your buffer size.
05The scanf() Function
📥 Understanding scanf() - Reading Input
scanf() is a function that reads formatted input from the keyboard. The name stands for "scan formatted".
📝 Usage Syntax
scanf("format string", &variable1, &variable2, ...);
⚠️ Notice the & (address-of operator) before variables!
1#include <stdio.h>23int main() {4 int age;5 char name[20];6 7 printf("Enter age: ");8 scanf("%d", &age); // & required!9 10 printf("Enter name: ");11 scanf("%s", name); // No & for arrays12 13 printf("Hello %s, you are %d!\n", name, age);14 return 0;15}Enter age: 25
Enter name: Bob
Hello Bob, you are 25!
⚠️ scanf Gotchas
- • Forgot &: Causes crash or undefined behavior
- • %s stops at space: "John Doe" reads only "John"
- • Buffer overflow: %s doesn't check array size
- • Leftover newline: %c may read the newline from previous input
06scanf Variants
| Function | Description | Use Case |
|---|---|---|
| scanf() | Read from stdin (keyboard) | Normal user input |
| fscanf() | Read from file stream | Parse file data |
| sscanf() | Read from string | Parse string data |
1#include <stdio.h>23int main() {4 char str[] = "Bob 25";5 char name[20];6 int age;7 8 // sscanf - parse from string9 sscanf(str, "%s %d", name, &age);10 printf("Name: %s, Age: %d\n", name, age);11 12 return 0;13}Name: Bob, Age: 25
07Character and String I/O
| Function | Prototype | Description |
|---|---|---|
| getchar | int getchar(void) | Returns next char from stdin (as int), or EOF on error |
| putchar | int putchar(int c) | Writes char c to stdout. Returns c or EOF on error |
| fgets | char *fgets(char *s, int n, FILE *stream) | Reads at most n-1 chars into s. Safe! Use stdin for keyboard |
| puts | int puts(const char *s) | Writes string s + newline to stdout. Returns non-negative or EOF |
1#include <stdio.h>23int main() {4 char ch;5 char name[50];6 7 // Single character8 ch = getchar(); // Read one char9 putchar(ch); // Print one char10 11 // Full line (with spaces!)12 fgets(name, 50, stdin);13 puts(name); // Print + newline14 15 return 0;16}Input: A
Output: A
Input: John Doe
Output: John Doe
💡 Use fgets() Instead of scanf() for Strings!
scanf("%s", ...) stops at whitespace and can overflow buffers.fgets() reads the entire line and is buffer-safe!
08main() with Command-Line Arguments
🎯 What are Command-Line Arguments?
Command-line arguments let you pass data to your program when you run it:
./program arg1 arg2 arg3
📝 main() Signatures
Without arguments:
int main(void)
int main()
With arguments:
int main(int argc, char *argv[])
int main(int argc, char **argv)
| Parameter | Name | Description |
|---|---|---|
| argc | Argument Count | Number of arguments (including program name) |
| argv | Argument Vector | Array of strings (the actual arguments) |
| argv[0] | Program Name | Always the name of the program |
| argv[1..n] | User Arguments | Arguments passed by the user |
1#include <stdio.h>23int main(int argc, char *argv[]) {4 printf("Arguments: %d\n", argc);5 6 for (int i = 0; i < argc; i++) {7 printf("argv[%d] = %s\n", i, argv[i]);8 }9 10 if (argc >= 2) {11 printf("Hello, %s!\n", argv[1]);12 }13 return 0;14}Arguments: 2
argv[0] = ./program
argv[1] = Bob
Hello, Bob!
🔧 String to Number Conversion
| Function | Converts To | Example |
|---|---|---|
| atoi() | int | atoi("42") → 42 |
| atof() | double | atof("3.14") → 3.14 |
1#include <stdio.h>2#include <stdlib.h>34int main(int argc, char *argv[]) {5 if (argc >= 2) {6 int num = atoi(argv[1]); // String to int7 printf("Number: %d\n", num);8 }9 return 0;10}Number: 42
09Common Mistakes
❌ Forgetting & in scanf
scanf("%d", num); // Wrong!
scanf("%d", &num); // Correct!
❌ Wrong format specifier
printf("%d", 3.14); // float with %d!
printf("%f", 3.14); // Correct!
❌ Buffer overflow with %s
char s[10];
scanf("%s", s); // Dangerous!
char s[10];
scanf("%9s", s); // Safe!
❌ Newline issue with %c
scanf("%c", &ch); // Reads leftover \\n
scanf(" %c", &ch); // Space skips whitespace
❌ Not checking return value
if (scanf("%d", &num) != 1) {
printf("Invalid input!\\n");
}
10Summary
🎯 Key Takeaways
- •printf: Formatted output to screen (variants: fprintf, sprintf, snprintf)
- •scanf: Formatted input from keyboard (variants: fscanf, sscanf)
- •Format specifiers: %d (int), %f (float), %c (char), %s (string), %p (pointer)
- •fgets(): Safer than scanf for strings (handles spaces, limits size)
- •argc/argv: Access command-line arguments in main()
- •Conversion: atoi(), atof(), strtol() for string to number
12Next Steps
Now that you understand input/output in C, learn about operators to perform calculations: