ACM必学 C/C++文件输入输出利器—freopen函数

相信很多人都用过freopen,但是是不是有时候在网上提交代码的时候需要把这句话注释掉,我一开始也是这样的,但还是觉得很麻烦,有时忘记注释,会多错一次,让人很不爽。

网上的资料很乱,什么代码都有,也不一定有效

但经过我的摸索,你只需要在main函数的开头写上以下代码

#ifdef ONLINE_JUDGE  
#else
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif

更简单地写法

#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif

因为大部分OJ都预定义了宏ONLINE_JUDGE

对于这种问题,大部分OJ系统是考虑到了这个问题,比如杭电的OJ系统,在FAQ里就有这个问题:
Q:Is there any way to determine if my program is runned at Online Judge or not ?
A:There is a conditional define of compiler called ONLINE_JUDGE. Example of using:
C/C++

#ifdef ONLINE_JUDGE
running on online judge
#else
you can do something here on your local computer
#endif

 

又比如:

ACM必学 C/C++文件输入输出利器—freopen函数_第1张图片


当然你事先要在和当前cpp相同位置创建好in.txt和out.txt文件,用于输入数据和观察结果

至此你不需要配置任何其他东西,就可以在本地利用输入输出文件安心调试你的代码,调试后直接拷贝,提交到各大OJ平台即可

该代码真的超级好用


例如:

#include 

using namespace std;

typedef long long ll;

int main(void) {

    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif

    int T;
    cin >> T;
    for (int cnt = 0; cnt < T; cnt++) {
        string s1, s2, s;
        cin >> s1 >> s2 >> s;
        
        if (s.find(s1) == string::npos || s.find(s2) == string::npos) {
            cout << "case #" << cnt << ":"  << endl;
            cout << 0 << endl;
        } else {
            int res = 0;
            int a1 = s.find(s1), a2 = s.rfind(s1);
            int b1 = s.find(s2), b2 = s.rfind(s2);

            int s1tos2 = abs(a1 - b2) - (int)s1.size();
            if (s1tos2 < 0) {
                s1tos2 = 0;
            }
            int s2tos1 = abs(a2 - b1) - (int)s2.size();
            if (s2tos1 < 0) {
                s2tos1 = 0;
            }

            res = max(s1tos2, s2tos1);

            cout << "case #" << cnt << ":"  << endl;
            cout << res << endl;
        }
    }

    return 0;
}

阅读更多文章,请看学习笔记汇总

 

你可能感兴趣的:(Algorithm)