写一个程序,它搜索一个包含int类型的数字的文件,将这些数字中的最大数和最小数写到屏幕。文件只包含int类型的数字,每个数字以空格或者换行符分割。
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
void get_max_min(ifstream& messy_file,ofstream& neat_file);
//流参数必须是传引用的
int main()
{
ifstream fin;
ofstream fout;
fin.open("infile.txt");
if(fin.fail())
{
cout<<"Input file opening failed.\n";
exit(1);
}
fout.open("outfile.txt");
if(fout.fail())
{
cout<<"Output file opening failed.\n";
exit(1);
}
get_max_min(fin,fout);
fin.close();
fout.close();
cout<<"End of program.\n";
return 0;
}
void get_max_min(ifstream& messy_file,ofstream& neat_file)
{
int max;
int min;
int next;
messy_file>>next;
max=min=next;
while(messy_file>>next)
{
if(next>max)
{
max=next;
}
if(next<min)
{
min=next;
}
}
cout<<"max:"<<max<<"\n";
cout<<"min:"<<min<<endl;
neat_file<<max<<endl;
neat_file<<min<<endl;
}