gogoWebsite

Two ways to read or output files (redirect version and fopen version)

Updated to 19 days ago

1. Redirect version

//Use files for reading and output (redirect version)
 //If you want standard input and file output, you just need to comment out the statements about file input, and the same applies to file input standard output.
 //If you want to go back to standard input and output, just comment out the local definition of the next line
 #define LOCAL
 #include<iostream>
 #include<cstdio>
 #include<fstream>
 using namespace std;
 int main()
 {
     #ifdef LOCAL
     freopen("","r",stdin); //scanf read from the file
     freopen("","w",stdout); //printf to file
     #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;
 }

version

//Use file input and output, but when redirection is prohibited, the following method is adopted
 //This is the file read in, the standard output is
 #include<iostream>
 #include<cstdio>
 #include<fstream>
 using namespace std;
 int main()
 {
     FILE *fin,*fout;
     fin=fopen("","rb"); //File reading
     //fout=fopen("","wb"); //Output to file
     //fin=stdin; //Change the fopen version of the program to read and write standard input and output
     fout=stdout;
     int x,n=0,min=100,max=-100,s=0;
     while(fscanf(fin,"%d",&x)==1) //scanf becomes 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 becomes fprintf
     fclose(fin); //Close two files
     fclose(fout);
     return 0;
 }