信奥练习的过程中,我们会在各种OJ平台刷题。

比如在核桃OJ上的第一道入门题:
https://htoj.com.cn/cpp/oj/problem/detail?pid=22069046618368
题目描述
这道题在看今天这篇文章之前,我们可能是这样写的:

#include<iostream>
using namespace std;
int main() 
{
    long a,b;
    cin>>a;
    cin>>b;
    cout<<a+b<<endl;
    return 0;
}

但是遇到下面这种输入输出怎么办?
oj平台题目中的输入输出

在C++中,我们可以使用重定向文件到标准输入输出流。
比如这道题的程序也可以写成下面这样:

#include <fstream>
#include <iostream>
// #define debug
using namespace std;

void solve() {
    long a, b;
    cin >> a >> b;
    cout << a + b << endl;
}

int main() {
#ifdef debug
    ifstream fin("oj/LGB2001_input.txt");
    ofstream fout("oj/LGB2001_output.txt");
    /***************这部分调试正常后可以删除start***************
    if (!fin) {
        cerr << "Error opening LGB2001_input.txt" << endl;
    }
    if (!fout) {
        cerr << "Error opening output.txt" << endl;
    }
    **************这部分调试正常后可以删除end******************/
    cin.rdbuf(fin.rdbuf());    // 重定向cin到文件
    cout.rdbuf(fout.rdbuf()); // 重定向cout到文件
#endif
    solve();
#ifdef debug
    fin.close();
    fout.close();
#endif
    return 0;
}

对上面的程序做一下解释:

#ifdef debug
 xxx
#endif

这段程序中的xxx 只有在我们显示定义了debug宏后才会运行。
而通过下面四行代码,我们就将oj/LGB2001_input.txtoj/LGB2001_output.txt 分别重定向到了cincout上。
接下来的代码中,cin>>就不会从控制台读取输入,而会直接从fin中读取;cout<<也不会写入到控制台,而会写入到fout中。
这样,遇到再长的输入都不用担心了。
比如在本例中,只需要将10230 21312复制到oj/LGB2001_input.txt文件中,程序执行完后,可以在 oj/LGB2001_output.txt 中看到程序运行结果。
如果要调试程序,可以使用 cerr 来进行控制台输出。

ifstream fin("oj/LGB2001_input.txt");
ofstream fout("oj/LGB2001_output.txt");
cin.rdbuf(fin.rdbuf());    // 重定向cin到文件
cout.rdbuf(fout.rdbuf()); // 重定向cout到文件

最后,再关闭finfout
这段代码中,真正核心的程序是solve()函数。

本地运行程序的时候,只需要将 #define debug 的注释去掉即可。

标签: 文件重定向优化输入输出, 信奥

上一篇: m1 macbook使用brew安装mysql
下一篇: 没有了

添加新评论