文件输入输出

文件输入输出的例子

以输出任意一组数的最大最小值,平均值为例

input:2 8 3 5 1 7 3 6

output:1 8 4.375

1重定向式

如果有#define LOCAL的时候执行#ifdef LOCAL 和#endif之间的语句, 没有定义LOCAL的时候不执行;

两个fopen加在main函数入口处,他将使得scanf从文件input.txt读入,printf写入文件output.txt

#include <stdio.h>
#define LOCAL int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int x, cnt, mi, ma, s; scanf("%d", &x); s = x; mi = x; ma = x; cnt = 1; while(scanf("%d", &x) == 1) { s += x; if(x < mi) mi = x; if(x > ma) ma = x; cnt++; } printf("%d %d %.3f ", mi, ma, (double)s/cnt);//注意括号位置,如果“s / cnt”在括号里面输出结果是错的,是个整数,看清double在括号里面 return 0; }

 2如果题目中禁止用重定向式输入,那可以采用下面方法

#include <stdio.h>
int main()
{
    FILE *fin, *fout;
    fin = fopen("data.in", "rb");
    fout = fopen("data.out", "wb");
    int x, cnt, mi, ma, s;
    fscanf(fin, "%d", &x);
    s = mi = ma = x;
    cnt = 1;
    while(fscanf(fin, "%d", &x) == 1)
    {
        s += x;
        if(x < mi) mi = x;
        if(x > ma) ma = x;
        cnt++;
    }
    fprintf(fout, "%d %d %.3f
", mi, ma, (double)s/cnt);
    fclose(fin);
    fclose(fout);
    return 0;
}

 3 C++样例

#include <fstream>
using namespace std;
ifstream fin("aplusb.in");
ofstream fout("aplusb.out");
int main()
{
    int a, b;
    while(fin >> a >> b) fout << a + b << "
";
    return 0;
}

4.C++样例修改

#include <fstream>
#include <iostream>
#define fin cin
#define fout cout
using namespace std;
int main()
{
    int a, b;
    while(fin >> a >> b) fout << a + b << "
";
    return 0;
}
原文地址:https://www.cnblogs.com/rain-1/p/4779983.html