作用
C++中常使用freopen函数输入测试数据以避免重复输入,实为一种简单而有效的手段。
用法
这里讲两种用法:
(首先将文件在程序目录里放好)
1.从文件中提取输入内容
freopen("文件名.文件格式","r",stdin);
此情况下文件需要以正确输入格式放在所写程序所在的目录下
#include<bits/stdc++.h>
using namespace std;
int main(){
int a[5];
int i;
//从filea.txt中提取输入内容
freopen("filea.txt","r",stdin);
for(i=0;i<5;i++){
//将filea.txt中的测试样例保存到a[i]中
scanf("%d",&a[i]);
}
for(i=0;i<5;i++){
printf("%d ",a[i]);
}
return 0;
}
将测试样例以正确格式输入到文件中
运行程序后输出结果如下
2.在文件中保存输出内容
freopen("文件名.文件格式","w",stdout);
#include<bits/stdc++.h>
using namespace std;
int main(){
//在fileb.txt中保存输出内容
freopen("fileb.txt","w",stdout);
cout<<"1 2 3 4 5";
return 0;
}
运行程序后文件内输出结果如下