03-进阶基础/07-文件读写与高级IO:修订间差异

来自三三百科
跳转到导航 跳转到搜索
->Importer
批量导入三三文档
 
33DAI留言 | 贡献
导入1个版本
(没有差异)

2026年5月20日 (三) 16:25的版本

文件输入输出(freopen

NOI 系列赛事通常要求使用文件输入输出:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    freopen("problem.in", "r", stdin);
    freopen("problem.out", "w", stdout);

    // 正常使用 cin / cout 即可
    int x;
    cin >> x;
    cout << x * 2 << "\n";

    return 0;
}

- "r":read,读模式 - "w":write,写模式 - 文件名在正式比赛的试卷首页会给出

输入输出加速

ios::sync_with_stdio(false);
cin.tie(0);

加上这两行后,cin/cout 的速度接近 scanf/printf

注意:加速后不要混用 cin/coutscanf/printf,否则会导致输出顺序混乱。

读入到文件末尾

当题目没有告诉具体有多少输入时,读入到 EOF:

// 方法一
int x;
while (cin >> x)
{
    // 处理 x
}

// 方法二(读取一行)
string s;
while (getline(cin, s))
{
    // 处理 s
}

保留小数位数

#include <iomanip>
cout << fixed << setprecision(3) << 1.0 / 3;
// 输出 0.333

完整加速框架

#include <bits/stdc++.h>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    // 你的代码

    return 0;
}

带文件 IO 的完整框架

#include <bits/stdc++.h>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    freopen("problem.in", "r", stdin);
    freopen("problem.out", "w", stdout);

    // 你的代码

    return 0;
}