输入输出重定向

对于某些竞赛,允许使用输入输出重定向;即输入数据和输出数据保存在文件中。

freopen("input.txt","r",stdin); //将文件的内容读入到程序中
freopen("output.txt","w",stdout);  //将程序的内容写到文件中

C语言的标准输入和输出为stdin和stdout,这两个变量定义的类型为FILE*,实际上标准的输入和输出也是对文件的操作。

当调用该函数时,需要引用头文件stdio.h,在使用freopen()之后的标准输出或输入会重新定向,而之前的不会变。

使用:
int main(){
    int a,b;

    freopen("C:\\Users\\dell\\Codeblocks\\紫书\\test.txt","r",stdin);
    freopen("C:\\Users\\dell\\Codeblocks\\紫书\\testt.txt","w",stdout);
    while(scanf("%d%d",&a,&b)==2){
        printf("%d %d\n",a,b);
    }

    return 0;


}

在竞赛中:

  1. 不能使用绝对路径或相对路径(不能形如c:\contest\test.out,只能是test.out)
  2. 程序名:test.c;输入文件:test.in;输出文件:test.out(这个.out和.in是类型后缀还是文件名的一部分?(可以定义为test.in.txt) 我估计为第二种情况,因为.in和.out文件好像不可以编辑(不太清楚,胡扯ing)(-_-||))

利用文件是一种很好的测试方法,但是如果采用标准输入输出,必须自我测试完之后进行删除,在这里可以运用一种方法:在本机测试使用重定向,提交到比赛,自动“删除”重定向语句。

#define LOCAL
#include<stdio.h>
#define INF 1000000000
int main(){
#ifdef LOCAL
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
#endif
    int x,n=0,min=INF,max=-INF,s=0;
    while(scanf("%d",&x)==1){
        s+=x;
        if(x<min){
            min=x;
        }
        if(x>max){
            max=x;
        }
    /*
        printf("x = %d, min = %d, max = %d\n",x,min,max);
    */
        n++;
    }
    printf("%d %d %.3f\n",min,max,(double)s/n);
    return 0;
}
  1. ifdef,endif:条件编译,在此程序中,如果#define 了LOCAL,那么就运行ifdef 的内容(也就是两条重定向语句)
  2. /* */视情况去掉
  3. 当提交的时候,只需要去掉#define LOCAL就可以;

猜你喜欢

转载自blog.csdn.net/lansehuanyingyy/article/details/80220357