First, take the data statistics as an example:
Calculates the maximum, minimum, and average values of a set of data.
If you do not need file operations, the following is the case:
#include<iostream>#include<fstream>#include<string>using namespace std;int main(){int x,n=0,min=99999,max=-99999,s=0;while(scanf("%d",&x)==1){s+=x;if(x<min) min=x;if(x>max) max=x;n++;}printf("%d %d %.3lf\n",min,max,double(s/n));return 0;}
It is troublesome to input new data each time. You can use the file method to calculate the data in a file.
The simplest way to use a file is to use input/output redirection. You can simply write the following two statements at the main function entry:
Freopen ("input.txt", "r", stdin );
Freopen ("output.txt", "W", stdout );
Then, scanfwill be read from the input.txt file and written to the output.txt file.
#include<iostream>#include<fstream>#include<string>using namespace std;int main(){int x,n=0,min=99999,max=-99999,s=0;while(scanf("%d",&x)==1){s+=x;if(x<min) min=x;if(x>max) max=x;n++;}printf("%d %d %.3lf\n",min,max,double(s/n));return 0;}
You can also use fopen without using redirection:
#include<stdio.h>#define INF 1000000int main(){FILE*fin,*fout;fin=fopen("data.in.txt","rb");fout=fopen("data.out.txt","wb");int x,n=0,min=INF,max=-INF,s=0;while(fscanf(fin,"%d",&x)==1){s+=x;if(x<min) min=x;if(x>max) max=x;n++;}fprintf(fout,"%d %d %.3lf",min,max,(double)s/n);fclose(fin);fclose(fout);return 0;}
Reading and Writing files in C ++:
#include <iostream>#include <fstream>#define INF 1000000using namespace std;ifstream fin("input.txt");ofstream fout("output.txt");int main(){int x,n=0,max=-INF,min=INF;double s=0.0;while(fin>>x) {s+=x;if(x<min) min=x;if(x>max) max=x;n++;}fout<<min<<" "<<max<<" "<<s/n<<endl;return 0;}