C++ 算法竞赛常用 IO 技巧笔记
一、标准 IO(终端输入输出)
✅ 1. 常用方式对比
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
cin / cout |
语法直观,支持类型推导 | 默认慢 | 小数据 / 关闭同步加速 |
scanf / printf |
速度快,兼容 C | 语法繁琐 | 中等数据 |
getline |
读取整行,适合字符串处理 | 需要注意换行符 | 字符串混合输入 |
getchar() |
每次读一个字符,速度极快 | 不方便读数字 | 快速读字符流 |
二、cin/cout 加速技巧
默认情况下,cin/cout 同步 stdio,效率较低。通过关闭同步并解绑流,可以显著提升性能:
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
🚫 注意
关闭同步后 不能混用 cin/cout 与 scanf/printf,否则行为未定义!
三、手写快读(推荐用于大数据)
适用于大量整数输入时,效率比 scanf 更快,模板如下:
inline int read() {
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') { if(ch == '-') f = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9') { x = x * 10 + (ch - '0'); ch = getchar(); }
return x * f;
}
- 可支持负数
- 也可扩展为读取
long long或double
四、标准输出技巧
推荐输出方式:
cout << val << '\n'; // ✅ 快,不自动flush
不推荐:
cout << val << endl; // ❌ 慢,会强制刷新缓冲区
五、读取整行 + 字符串解析技巧
适合处理如下类型输入:
10 20 30 40
a b c d
string line;
getline(cin, line);
stringstream ss(line);
int x;
while (ss >> x) {
// 逐个读入数字
}
六、EOF 输入方式(多组输入)
OJ 常见“读到文件末尾为止”的格式:
int a, b;
while(cin >> a >> b) {
// 多组测试样例
}
scanf 版本:
while(scanf("%d%d", &a, &b) != EOF) {
...
}
七、浮点数精度控制
cout << fixed << setprecision(6) << x;
或
printf("%.6lf\n", x);
八、文件 IO(读写文件时使用)
OJ一般不需要文件IO,但调试 / 离线评测 / 批量测试时非常有用
#include <fstream>
ifstream fin("input.txt");
ofstream fout("output.txt");
int a;
fin >> a;
fout << a << '\n';
fin.close();
fout.close();
✅ 同样支持:
getline(fin, s):读取一整行stringstream搭配文件行处理
九、常见 IO 问题总结
| 问题类型 | 原因/表现 | 解决建议 |
|---|---|---|
| TLE(时间超限) | 输入数据太大,使用 cin/endl | 使用 ios::sync_with_stdio(false) 或手写快读 |
| 输出格式错误 | 空格/换行位置不对,浮点精度不一致 | 仔细对照样例,统一输出格式 |
| 读取失败 | getline 遇到换行符未清空缓存区 | 搭配 cin.ignore() |
| 混用 IO 崩溃 | cin 与 scanf 混用 | 保持 IO 方法一致性 |
| 文件读写失败 | 文件路径错误、忘记关闭流 | 路径确认,使用 close() |
十、IO模板推荐
模板一:cin/cout 快速 IO 模板(推荐)
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
for (int x : a) cout << x << '\n';
return 0;
}
模板二:文件 IO 模板
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
int n;
fin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) fin >> a[i];
for (int x : a) fout << x << '\n';
fin.close();
fout.close();
return 0;
}
模板三:快读模板(纯整数输入)
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') { if(ch == '-') f = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9') { x = x * 10 + (ch - '0'); ch = getchar(); }
return x * f;
}
int main() {
int n = read();
for (int i = 0; i < n; ++i) {
int x = read();
printf("%d\n", x);
}
return 0;
}

浙公网安备 33010602011771号