C: Input and Output

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: MOTO🏷 Category: C Tutorial

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.

Reference entries in this section: printf scanf

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%
C
// 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;
}
TEXT
Age: 25, Height: 175.5, Grade: A

(2) Width and Alignment

You can insert numbers between % and the format specifier to control output width:

C
// 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;
}
TEXT
[   42]
[42   ]
[00042]
[  +42]

(3) Floating-Point Precision

C
// 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;
}
TEXT
Default:  3.141593
2 places: 3.14
6 places: 3.141593
8.2:          3.14
💡 Tip: %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

C
// 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;
}
TEXT
Enter your age: 20
Enter your score: 92.5
Age: 20, Score: 92.5
⚠️ Note: scanf's variable arguments must be preceded by & (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

C
// 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;
}
TEXT
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

C
// 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;
}
⚠️ Note: Adding a space before %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:

C
// 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;
}
TEXT
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").

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;
}
TEXT
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:

C
// 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;
}
TEXT
Enter a line of text: Hello World!
Hello World!
💡 Tip: 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

C
// 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;
}
TEXT
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)

TEXT
scanf(" %c", &ch);

The space skips all whitespace characters (including newlines, spaces, and tabs).

Solution 2: Use getchar() to absorb the leftover

C
// I/O operation
scanf("%d", &num);
// I/O operation
getchar();
// I/O operation
scanf("%c", &ch);

Solution 3: Clear the input buffer

TEXT
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
⚠️ Note: Don't use 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 Yourself
TEXT
Enter 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:

▶ Try it Yourself
TEXT
Enter a line of text: Hello 2024!
Letters: 5, Digits: 4

▶ Example 3: printf Format Combinations

▶ Try it Yourself

输出:

TEXT
Name: 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:

C
// 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;
}
TEXT
Hello, World!
Auto newline, no need for \n
💡 Tip: 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.

Reference entries in this section: printf scanf

❓ FAQ

Q Why do scanf variables need & in front?
A scanf needs to know where to store the value, and & takes the variable's address. Only array names don't need it, because an array name is already the address of its first element.
Q scanf("%c") skipped my input — what happened?
A There's a leftover newline in the buffer from a previous input. Add a space before %c: scanf(" %c", &ch) to skip whitespace.
Q Can printf and scanf format specifiers be uppercase?
A Some can. %d lowercase corresponds to int; uppercase %D is non-standard. But %x prints lowercase hex (abcdef) while %X prints uppercase (ABCDEF) — this is valid.
Q How do I safely read a string with spaces?
A scanf("%s") stops at whitespace. Use fgets(name, sizeof(name), stdin) to read an entire line — it supports spaces and is safer.

📖 Summary

📝 Exercises

  1. Write a program that reads a circle's radius and outputs its area and circumference using printf's %.2f format.
  2. Write a program that uses getchar() to read a line of input and counts how many uppercase and lowercase letters it contains.
  3. Write a program that reads an integer and outputs it in decimal (%d), hexadecimal (%x), and octal (%o) formats.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏