使用文件进行读取或输出的两种方式(重定向版和fopen版)

1.重定向版

//利用文件进行读取和输出(重定向版)
//如果想要标准输入而文件输出时,只需将关于文件输入的语句注释掉即可,文件输入标准输出同理
//如果想回到标准输入输出时,只需将下一行的本地定义注释掉即可
#define LOCAL
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
    #ifdef LOCAL
    freopen("input.txt","r",stdin);                 //scanf从文件中读取
    freopen("output.txt","w",stdout);               //printf到文件
    #endif // LOCAL
    int x,n=0,min=100,max=-100,s=0;
    while(scanf("%d",&x)==1)
    {
        s+=x;
        if(min>x) min=x;
        if(max<x) max=x;
        n++;
    }
    printf("%d %d %.3f\n",min,max,(double)s/n);
    return 0;
}

2.fopen版

//使用文件输入输出,但当禁止使用重定向的方式时,采用如下方法
//此时为文件读入,标准输出
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
    FILE *fin,*fout;
    fin=fopen("input.txt","rb");                //文件读取
    //fout=fopen("output.txt","wb");                  //输出到文件
    //fin=stdin;                                              //把fopen版的程序改成读写标准输入输出
    fout=stdout;
    int x,n=0,min=100,max=-100,s=0;
    while(fscanf(fin,"%d",&x)==1)                   //scanf变为fscanf
    {
        s+=x;
        if(min>x) min=x;
        if(max<x) max=x;
        n++;
    }
    fprintf(fout,"%d %d %.3f\n",min,max,(double)s/n);           //printf变为fprintf
    fclose(fin);                                                    //关闭两个文件
    fclose(fout);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值