In C++, input and output (I/O) are core operations for interacting with users. This article will delve into two commonly used methods: the object-oriented <span>cin/cout</span> streams and the C-style <span>printf/scanf</span> functions, helping you handle program interactions flexibly.
1. C++ Stream I/O:<span>cin</span> and <span>cout</span>
1. Standard Output Stream <span>cout</span>
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl; // endl indicates a new line and flushes the buffer
cout << "7 * 8 = " << 7 * 8; // automatic type deduction, no format specifier needed
return 0;
}
Features:
- Uses
<span><<</span>output operator - Automatically recognizes data types (no need for
<span>%d</span>format specifiers) <span>endl</span>not only creates a new line but also forces a buffer flush
2. Standard Input Stream <span>cin</span>
int age;
double salary;
string name;
cout << "Please enter your name, age, and salary:";
cin >> name >> age >> salary; // consecutive input
cout << name << ", " << age << " years old, salary: " << salary;
Note:
- Spaces and new lines are treated as input delimiters
- Type mismatches in input can lead to subsequent read failures
2. C-style I/O:<span>printf</span> and <span>scanf</span>
Include the C library:<span>#include <cstdio></span>
1. Formatted Output <span>printf</span>
int num = 42;
double pi = 3.1415926;
char ch = 'A';
printf("Integer: %d\n", num); // %d for integer
printf("Character: %c\n", ch); // %c for character
printf("Floating point: %.2f\n", pi); // %.2f for two decimal places
printf("Hexadecimal: 0x%X\n", num); // %X for uppercase hexadecimal
Common format specifiers:
| Symbol | Meaning | Example |
|---|---|---|
<span>%d</span> |
Decimal integer | <span>printf("%d", 100)</span> |
<span>%f</span> |
Floating point | <span>printf("%.2f", 3.1415)</span> |
<span>%c</span> |
Single character | <span>printf("%c", 'A')</span> |
<span>%s</span> |
String | <span>printf("%s", "Hello")</span> |
<span>%p</span> |
Pointer address | <span>printf("%p", &num)</span> |
2. Formatted Input <span>scanf</span>
int id;
char name[20];
float score;
printf("Enter ID, name, and score:");
scanf("%d %s %f", &id, name, &score); // array name is the address
printf("ID:%d, %s's score: %.1f", id, name, score);
Key points:
- Must use variable addresses (
<span>&</span>operator) - String input requires character arrays (
<span>char[]</span>) - Format specifiers must strictly match variable types
3. Comparison and Selection Guide
| Feature | <span>cin/cout</span> |
<span>printf/scanf</span> |
|---|---|---|
| Type Safety | Automatic type deduction | Manual format specifier matching required |
| Performance | Slower (default synchronized with C streams) | Faster |
| Formatting Control | Requires <span><iomanip></span> library support |
Native support for fine formatting |
| Prevention of Buffer Overflow | <span>string</span> automatically manages memory |
<span>%s</span> may overflow (dangerous!) |
| Code Readability | Chained operations are more intuitive | Format strings and parameters are separated |
When to choose?
- Recommended
<span>cin/cout</span>: Daily interactions, type safety priority, using C++ strings - Consider
<span>printf/scanf</span>: High-performance scenarios, fine formatting needs, compatibility with C code
4. Pitfall Guide
1. Mixing usage leads to buffer confusion
int num;
char ch;
cout << "Enter a number:";
cin >> num;
cout << "Enter a character:";
cin.get(ch); // Captures the newline character from the previous input!
Solution:
cin.ignore(); // Clear residual characters in the input buffer
cin.get(ch); // Correctly get the new character
2. <span>scanf</span> input string safety issues
char buffer[10];
scanf("%s", buffer); // Input exceeding 10 characters will cause buffer overflow!
Safe practice:
scanf("%9s", buffer); // Limit maximum read length
5. Best Practice Recommendations
-
Prefer C++ style Modern C++ projects should prioritize type-safe
<span>cin/cout</span>, especially when used with<span>std::string</span>:string user; getline(cin, user); // Safely read an entire line -
Disable stream synchronization to improve performance In pure C++ environments, synchronization can be disabled:
ios::sync_with_stdio(false); // Speed up cin/cout -
Use
<span>printf</span>for complex formatting When alignment and precision control are needed:printf("%-10s | %8.2f\n", "Product A", 128.5); // Left-align name, right-align price
Mastering both I/O methods is like having a dual arsenal. <span>cin/cout</span> provides safe and convenient daily interactions, while <span>printf/scanf</span> are powerful tools for high performance and precise control. Understanding their underlying mechanisms allows you to navigate between memory safety and execution efficiency with ease!
Java learning materials available
C language learning materials available
Frontend learning materials available
C++ learning materials available
PHP learning materials available