C: Input and Output
Input and output are like a conversation between you and the computer — printf is the computer talking to you, scanf is you talking to the computer. Get the format right, or you'll be talking past each other.
1. printf Formatted Output
printf stands for "print formatted." Its first argument is a format string, followed by the values to output.
(1) Basic Format Specifiers
| Specifier | Purpose | Example | Output |
|---|---|---|---|
%d |
Decimal integer | printf("%d", 42) |
42 |
%f |
Floating-point | printf("%f", 3.14) |
3.140000 |
%c |
Single character | printf("%c", 'A') |
A |
%s |
String | printf("%s", "hi") |
hi |
%x |
Hexadecimal | printf("%x", 255) |
ff |
%o |
Octal | printf("%o", 8) |
10 |
%p |
Pointer address | printf("%p", &a) |
Address value |
%% |
Literal percent sign | printf("100%%") |
100% |
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age = 25;
// Variable declaration
float height = 175.5f;
// Variable declaration
char grade = 'A';
// I/O operation
printf("Age: %d, Height: %.1f, Grade: %c\n", age, height, grade);
// Return result
return 0;
}
Age: 25, Height: 175.5, Grade: A
(2) Width and Alignment
You can insert numbers between % and the format specifier to control output width:
%5d: Minimum 5 characters wide, right-aligned%-5d: Minimum 5 characters wide, left-aligned%05d: Pad with zeros up to 5 digits
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int num = 42;
// I/O operation
printf("[%5d]\n", num);
// I/O operation
printf("[%-5d]\n", num);
// I/O operation
printf("[%05d]\n", num);
// I/O operation
printf("[%+5d]\n", num);
// Return result
return 0;
}
[ 42]
[42 ]
[00042]
[ +42]
(3) Floating-Point Precision
%.2f: 2 digits after the decimal point%8.2f: Total width at least 8 characters, 2 digits after the decimal point%-8.2f: Left-aligned version
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
double pi = 3.14159265358979;
// I/O operation
printf("Default: %f\n", pi);
// I/O operation
printf("2 places: %.2f\n", pi);
// I/O operation
printf("6 places: %.6f\n", pi);
// I/O operation
printf("8.2: %8.2f\n", pi);
// Return result
return 0;
}
Default: 3.141593
2 places: 3.14
6 places: 3.141593
8.2: 3.14
%f defaults to 6 decimal places. Use %.0f to hide the decimal portion entirely.
2. scanf Reading Input
scanf stands for "scan formatted." It reads data from standard input according to the format string and stores it in variables.
(1) Basic Usage
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age;
// Variable declaration
float score;
// I/O operation
printf("Enter your age: ");
// I/O operation
scanf("%d", &age);
// I/O operation
printf("Enter your score: ");
// I/O operation
scanf("%f", &score);
// I/O operation
printf("Age: %d, Score: %.1f\n", age, score);
// Return result
return 0;
}
Enter your age: 20
Enter your score: 92.5
Age: 20, Score: 92.5
& (the address-of operator), telling scanf "store the value at this address." Forgetting & is the most common beginner mistake — the program won't error out but will crash.
(2) Reading Multiple Values
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a, b, c;
// I/O operation
printf("Enter three integers (separated by spaces): ");
// I/O operation
scanf("%d %d %d", &a, &b, &c);
// I/O operation
printf("You entered: %d, %d, %d\n", a, b, c);
// Return result
return 0;
}
Enter three integers (separated by spaces): 10 20 30
You entered: 10, 20, 30
By default, scanf uses whitespace (spaces, newlines, tabs) to separate different values.
(3) Reading Characters and Strings
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
char ch;
char name[20];
// I/O operation
printf("Enter a character: ");
// I/O operation
scanf(" %c", &ch);
// I/O operation
printf("Enter your name (no spaces): ");
// I/O operation
scanf("%s", name);
// I/O operation
printf("Character: %c, Name: %s\n", ch, name);
// Return result
return 0;
}
%c (" %c") skips whitespace characters, otherwise it will read the leftover newline from previous input. %s reads a string but stops at whitespace. name is an array name, which is already an address, so no & is needed.
(4) scanf's Return Value
scanf returns the number of successfully read variables. This feature can be used to validate input:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int num;
// I/O operation
printf("Enter an integer: ");
// Variable declaration
int result = scanf("%d", &num);
// Conditional check
if (result == 1) {
// I/O operation
printf("Successfully read: %d\n", num);
} else {
// I/O operation
printf("Invalid input!\n");
}
// Return result
return 0;
}
Enter an integer: abc
Invalid input!
3. getchar and putchar
getchar() reads a single character from the keyboard, and putchar() outputs a single character to the screen. They're simpler and more efficient than scanf("%c") and printf("%c").
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
char ch;
// I/O operation
printf("Enter a character: ");
ch = getchar();
// I/O operation
printf("You entered: ");
// I/O operation
putchar(ch);
// I/O operation
putchar('\n');
// Return result
return 0;
}
Enter a character: X
You entered: X
(1) Reading an Entire Line
getchar() combined with a loop can read an entire line until a newline is encountered:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
char ch;
// I/O operation
printf("Enter a line of text: ");
// While loop
while ((ch = getchar()) != '\n') {
// I/O operation
putchar(ch);
}
// I/O operation
putchar('\n');
// Return result
return 0;
}
Enter a line of text: Hello World!
Hello World!
while ((ch = getchar()) != '\n') is a classic idiom: first read a character into ch, then check if it's a newline. Note that the outer parentheses around the assignment are mandatory.
4. Buffer Issues
C's standard input uses line buffering: the entire line of data is only delivered to the buffer for the program to read after the user presses Enter. This can cause some confusing problems.
(1) Problem: scanf %c Reads a Leftover Newline
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int num;
// Variable declaration
char ch;
// I/O operation
printf("Enter an integer: ");
// I/O operation
scanf("%d", &num);
// I/O operation
printf("Enter a character: ");
// I/O operation
scanf("%c", &ch);
// I/O operation
printf("Integer=%d, Character=%d\n", num, ch);
// Return result
return 0;
}
Enter an integer: 42
Enter a character: Integer=42, Character=10
After typing 42 and pressing Enter, the buffer contains 42\n. scanf("%d") reads 42, and scanf("%c") immediately reads that leftover \n (ASCII code 10), without waiting for you to type a character.
(2) Solutions
Solution 1: Add a space before %c (recommended)
scanf(" %c", &ch);
The space skips all whitespace characters (including newlines, spaces, and tabs).
Solution 2: Use getchar() to absorb the leftover
// I/O operation
scanf("%d", &num);
// I/O operation
getchar();
// I/O operation
scanf("%c", &ch);
Solution 3: Clear the input buffer
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
fflush(stdin) to clear the input buffer — it's undefined behavior in standard C. Some compilers support it, but it's not portable.
▶ Example
Write a program that reads both an integer and a character, properly handling buffer leftovers:
▶ Try it YourselfEnter your age: 25
Enter your gender (M/F): M
Age: 25, Gender: M
▶ Example
Use getchar() to read character by character and count the number of letters and digits in a line:
Enter a line of text: Hello 2024!
Letters: 5, Digits: 4
▶ Example 3: printf Format Combinations
▶ Try it Yourself输出:
TEXTName: Alice Age: 25 (hex: 19) PI: 3.14 (scientific: 3.14e+00) Grade: A (ASCII 65) Width demo: [ 25] Left demo: [25 ]!
5. puts and fputs
puts() outputs a string and automatically appends a newline. It's simpler than printf and ideal for plain text output:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// I/O operation
puts("Hello, World!");
// I/O operation
puts("Auto newline, no need for \\n");
// Return result
return 0;
}
Hello, World!
Auto newline, no need for \n
puts() is more efficient than printf("%s\n", ...) because it doesn't need to parse a format string. When you don't need formatting, prefer puts.
❓ FAQ
& in front?& takes the variable's address. Only array names don't need it, because an array name is already the address of its first element.scanf(" %c", &ch) to skip whitespace.%d lowercase corresponds to int; uppercase %D is non-standard. But %x prints lowercase hex (abcdef) while %X prints uppercase (ABCDEF) — this is valid.scanf("%s") stops at whitespace. Use fgets(name, sizeof(name), stdin) to read an entire line — it supports spaces and is safer.📖 Summary
printfuses format specifiers to control output: width, precision, alignment, paddingscanfrequires&before variables; add a space before%cto avoid reading leftover newlinesgetchar/putcharare efficient choices for single-character I/O- Line buffering causes leftover data issues between scanf and getchar calls
- scanf's return value can be used to validate whether input was successful
📝 Exercises
- Write a program that reads a circle's radius and outputs its area and circumference using
printf's%.2fformat. - Write a program that uses
getchar()to read a line of input and counts how many uppercase and lowercase letters it contains. - Write a program that reads an integer and outputs it in decimal (
%d), hexadecimal (%x), and octal (%o) formats.